"Exploring the art of extracting a string based on a specific pattern with JavaScript

Looking to format a phone number string by adding an extension? Consider alternatives to inserting at each index. For example, if the input is 1234567891346, the desired output would be (123) - 456 - 7891 Ext - 346.

let phoneStr = '12345678912346';
     let phoneNo = [ '(' , phoneStr[0], phoneStr[1], phoneStr[2], ')', ' - ', 
                    phoneStr[3], phoneStr[4], phoneStr[5], ' - ',
                    phoneStr[6], phoneStr[7], phoneStr[8], phoneStr[9], ' Ext - ',
                    phoneStr[10], phoneStr[11], phoneStr[12], phoneStr[13], phoneStr[14]];
     console.log(phoneNo.join("").replace(/,/g , ""));

Answer №1

const formattedPhoneNo = `(${phoneStr.slice(0,3)}) - ${phoneStr.slice(3,5)} - ${phoneStr.slice(5,10)} Ext - ${phoneStr.slice(10, 14)}`

If in doubt, consider using babel for compatibility

Answer №2

To achieve the desired formatting of a phone number, one can utilize the slice() method available in Array.prototype:

let phoneNumber= '12345678912346';
let formattedNumber = '(' + phoneNumber.slice(0,3) + ') - ' + phoneNumber.slice(3,6) + ' - ' + phoneNumber.slice(6,10) + ' Ext - ' + phoneNumber.slice(10,15);
console.log(formattedNumber);

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

Warning: Nodemailer has issued a deprecation warning regarding the outdated `punycode` module

Looking to automate daily email sending through a Gmail account, I have been experimenting with nodemailer and crafted this simple test code: const fs = require('fs'); const path = require('path'); const nodemailer = require('nodem ...

Ways to troubleshoot a validation error when the user selects the captcha

I have incorporated a captcha into my asp.net MVC core web application using the following code: <div class="form-group"> <div class="col-md-2"></div> <div class=" ...

Is there a way to incorporate Actions into the tool-bar on the Dashboard of Jupyter Notebook?

I am currently in the process of developing a customized front-end extension for Jupyter Notebook. I plan to have buttons on both the Notebook Dashboard and Editor that will trigger various actions. Similar to the existing "Move" and "Duplicate" buttons, ...

AngularJS enhanced dropdown navigation bar built using Bootstrap styling

I'm currently learning how to implement Bootstrap, but I've run into an issue. I created a dropdown in the navigation bar, but when I clicked on it, the dropdown didn't collapse as expected. The class="dropdown" didn't change to class= ...

Click on all elements within a specified division

I'm encountering an issue with selecting all the content within a specific div element. Here's a demonstration of the problem: http://jsfiddle.net/KcX6A/304/ Currently, only the first line of text is being selected, while the rest is being igno ...

It appears that Next.js's useDebouncedCallback function is not effectively delaying the request

I am currently learning Next.js and trying to work through the tutorial. I have hit a roadblock on this particular page: https://nextjs.org/learn/dashboard-app/adding-search-and-pagination Despite conducting an extensive web search, I couldn't find a ...

Load gallery thumbnails dynamically using JavaScript or jQuery

Currently, I have implemented TN3 gallery in a WordPress website (not as a plugin, but as a jQuery library). While the large images in the gallery load dynamically and do not affect the page load, the thumbnails are all loaded at once, even if they are no ...

Identifying the moment when the body scroll reaches the top or bottom of an element

I have been experimenting with javascript and jquery to determine when the window scroll reaches the top of a specific element. Although I have been trying different methods, I have yet to see any successful outcomes: fiddle: https://jsfiddle.net/jzhang17 ...

Obtaining a result from a Promise in AngularJS

Here is a snippet of an Angular JS Service that I have: 'use strict'; app.factory('loggedService', ['$http', 'authService', 'customerService', function ($http, authService, customerService) { var out = ...

Utilizing NodeJS and Express to efficiently share sessions across various routes

I have a Node.js web application built with Express that has multiple routes. These routes need to be able to access and share the session data when interacting with users. The routes are separated into different js files from the main app file, app.js. I ...

Encountering the error "TypeError: Unable to access property 'controls' of undefined" when utilizing formArray in Reactive forms

Hi there, I am currently working on creating a dynamic form using formArray in Angular. However, I have run into an issue with the error message "TypeError: Cannot read property 'controls' of undefined." import { Component, OnInit } from ' ...

What is the most efficient method for implementing absolute imports in Webpack 2?

I'm currently working on configuring Webpack for a React project and I'm looking to streamline how I import my components. Ideally, I want to import components like this: import ComponentName from "components/ComponentName" Instead of the more ...

Elegant switch in jQuery

I am trying to use jQuery to create an animated toggle button. The toggle function is working correctly, but I am having trouble adjusting the speed and smoothness of the animation. After researching different methods and attempting to modify the values i ...

Unable to adjust the color of the font

I am trying to create a toggle effect for the colors of a fontawesome icon when clicking on a text link, but it only works with a button. Here is the HTML code snippet: <div class='post'> <i class='fas fa-heart' id='h ...

The parameter `Matcher` does not accept the argument type `content: string, node: Element | null, returning boolean | null | undefined`

I encountered an issue with my React Typescript app while unit testing, where I had to use the following code to locate an element based on its textContent: import { screen } from "@testing-library/react"; export function getByTextContent(textMa ...

What advantages does the Step function (AWS) offer compared to setTimeout (Javascript) for scheduling tasks?

I am currently in the process of developing an API service that allows any client to provide me with their HTTP request along with the desired time in seconds for execution. I have considered two potential approaches to achieve this: Utilizing a lambda f ...

Is there a way to differentiate the color of an active link from an inactive one, so users can easily identify which link they are currently viewing?

How can I customize the color of text for the active page on my website's sidebar? For example, I have two hyperlinks, one for HOME and one for ABOUT. When a user clicks on the HOME link, I want the text color to change to green while the ABOUT link r ...

Combining various files to create a single file using gulp

When using gulp, I have multiple files that need to be parsed into arrays of objects individually. After parsing them, I want to merge all these arrays into one and create a single output file based on the combined array. file1 is parsed into array1 file2 ...

How can I load a specific div region using ajax for submitting a form?

I'm not sure if my approach is correct. On my main page, I have some information displayed. When you click a button, the form will load from a separate file: $('#viewport').load('/views/myView.php #targetDiv') This works fine ...

Incorporate axios within getStaticProps while utilizing Next.js

I am working on a new project where I am utilizing axios to handle request data. However, I am facing an issue when using axios in the getStaticProps function which results in an error on my index.js page. Here is a snippet of my index.js code: import ...