Retrieve characters preceding and following a space (JavaScript)

In my Angular component, I have a phone number field.

For example, +36 42534534534

I am trying to extract the code before the space and the phone number after the space.

This is how I am currently handling it:

set phoneNumberResult(value: string) {
    if (this.phoneNumberResult !== value) {
        this.phoneCode = value.substr(0, 3);
        this.phoneNumber = value.substr(5, value.length - 5);
        this.changed.forEach(f => f(value));
    }
}

However, the phone code can vary in length (3, 4, or 5 symbols), so I need to get all characters before the space as well as those after the space to determine both the phoneCode and phoneNumber.

What would be the correct approach to achieve this?

Answer №1

Experiment with using the split() method along with space.

let value = `+36 42534534534`
let valueSplit = value.split(' ');
let phoneCode = valueSplit[0]
let phoneNumber = valueSplit[1]

console.log(phoneCode)
console.log(phoneNumber)

Answer №2

If the format of the string input always consists of a prefix separated by a number with an empty space, you can easily utilize the split method (learn more about split here).

set phoneNumberResult(value: string) {
    if (this.phoneNumberResult !== value) {
        let [phoneCode, phoneNumber] = value.split(' ');
        this.phoneCode = phoneCode;
        this.phoneNumber = phoneNumber;
        this.changed.forEach(f => f(value));
    }
}

In your scenario, using split will result in an array where the first element represents the left side of the split string, and the second element represents the right side.

Feel free to experiment using this sample fiddle: https://jsfiddle.net/mcxuorhf/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding new fonts to an Angular 2 web page

I am working on an Angular 2 application and I want to incorporate wrapbootstrap. However, I am facing an issue with the fonts (bootstrap, font-awesome, google) and I am not sure how to include them. While using the css file for wrapbootstrap, I am gettin ...

Conceal user input field in React using a hook

I am looking for assistance with a form that has 4 input fields: username, password, email, and mobile. My goal is for the email field to disappear if an '@' symbol is typed in the username field, and for the mobile field to disappear if any digi ...

Using Angular 2: Applying a specific class to a single element with [ngClass]

I have a header table with arrows indicating sorting order, using Bootstrap icons. However, when I click on a column, all columns receive the icon class. Here is an example of what I mean: https://i.sstatic.net/CAS81.png Below is the code snippet: HTML ...

Is there a workaround for utilizing reducer dispatch outside of a React component without relying on the store?

Recently, I implemented a reducer in my project that involves using react, typescript and nextJS. I am wondering if there is a method to trigger the reducer outside of a react component, such as from an API service. While searching for solutions, most re ...

Small jumps occur when implementing the scrollTop jquery animation

I've encountered an issue with the scrollTop jquery animation that I can't seem to resolve. It seems to micro-jump right before the animation, especially when there is heavier content. I'm puzzled as to why this is happening... Here's ...

What is the best way to manage a new Error in Node.js while utilizing ES6 Symbols?

In my node.js application, I am implementing an endpoint using ES6 Symbols. Here is an example: // ES6 Symbol Method const taskCreationMethod = { [Symbol.taskMethod]() { return { storeCheckFunc: async function(storeId, employeeId) ...

JavaScript code to access each nested object and flatten only the top level of the object

Currently, I am working with an array of objects that has a nested structure like this: props: { dog: { default: '', type: String }, cat: { default: '', type: String }, ...

What is the best way to delete a parent div without losing its inherited CSS properties?

My current objective involves the following: <div id="table"> <div id="user"></div> <div id="user1"></div> </div> Upon clicking a button, the following actions take place: $("#body").append("<div id=\"user-wra ...

Perform a GET request using Node and React to validate login credentials

I recently started working on a MERN application and I'm trying to build it without relying too much on tutorials. I have successfully created a component for registration that stores information in the database, but now I am facing an issue with the ...

Effortlessly collapsing cards using Angular 2 and Bootstrap

Recently delving into Angular 2 and Bootstrap 4, I set up an about page using the card class from Bootstrap. Clicking on a card causes it to expand, and clicking again collapses it. Now, I want to enhance this by ensuring that only one card is open at a ti ...

(perhaps) just a question regarding AJAX and PHP

Having a bit of trouble here - I have two files, main.html and processing.php. In the php file, I am trying to update a specific element on main.html, but I can't seem to retrieve either the html or javascript value from main.html For instance, main. ...

Verify that all arrays that are returned consist solely of the value false

console.log(allStatuses); This variable shows two arrays: [true, false, false, false, false] [true, false, false, true, false] In some cases, additional arrays will be displayed with true/false values. I am interested in determining whether all the ar ...

Obtain element by selecting a specific class using Javascript

<select class="tmcp-field tillagg-width tm-epo-field tmcp-select" name="tmcp_select_30" data-price="" data-rules="" data-original-rules="" id="tmcp_select_ ...

`Can controllers be included in route or template definitions?`

When it comes to defining a route with a template, there are two main ways to set the controller for the view: In the route: $routeProvider .when('/phone/:phoneId', { controller: 'PhoneDetailController', templateUrl: &ap ...

How to nullify the valueChanges pipe in Angular RxJS until the observable is resolved

A challenge I am facing is piping the valueChanges from a select element to trigger the appropriate API request and displaying a spinner until the response is received. Additionally, I am trying to utilize publish() and refCount() methods so that I can use ...

Ways to parse a JSON array using Javascript in order to retrieve a specific value if it is present

Below is the JSON code stored in an array: { "kind": "urlshortener#url", "id": "http://goo.gl/2FIrtF", "longUrl": "http://hike.com/?utm_source=facebook", "status": "OK", "created": "2015-09-22T13:45:53.645+00:00", "analytics": { "allTime": { ...

What could be causing the Logical Or to fail in my function?

How can I adjust the following sample code to check for not only empty keys but also null and undefined? I attempted: (obj[key] !== '' || obj[key] !== null || (obj[key] !== undefined) However, that approach caused issues and did not function c ...

Viewing the photo container before uploading while having text overlap

I'm encountering an issue where the image previews are overlapping with the text in another div. Here are the screenshots: the first one shows how it looks before the preview, and the second one shows what happens when images are added: https://i.sst ...

Angular universal server-side rendering is functional on my local machine, however, it is encountering issues when

I've been delving into Angular Universal with nestjs. Everything seems to be running smoothly on my localhost at port 4000, but once I deploy the build on Netlify, the site functions properly except for Angular Universal. On my local machine, I use n ...

Utilizing Dynamic Components and the Event Emitter Feature in Angular Version 5

As a newcomer to Angular, I am currently grappling with the concept of dynamic components within my project. Specifically, I am working on implementing functionality where a user can select a row in a component and then click a button to open a modal (cont ...