简体   繁体   中英

Format number using RegExp in javascript

I have a number like below

var number = '12345678904444'

and i want like this

(123) 456-7890x4444

Format is (###) ###-####x####.

How can i achieve this.

就其价值而言,这就是 RegExp 解决方案的样子 ;-)

number.replace(/^(\d{3})(\d{3})(\d{4})(\d{4})$/, '($1) $2-$3x$4.');

You can use the javascript string split method :

var number = '12345678904444';
var numbers_array = numbers.split(""); 

Then you can use the array of the numbers to create a new string, following the format you want.

I'm sure you can do that !

If you want to format a number in Javascript, your best bet is to use String.slice() to extract the number parts you need, then contact them together using + .

DO NOT USE REGEX FOR THIS!! If your string in this has an error and can't be parsed properly, you run the risk of catastrophic backtracking, where your processing lasts really, really long.

I would prefer this:

var num = '1234567890x4444';
var first = num.substr(0,3), second = num.substr(3,3), last = num.substr(6);
var formatted = '('+first+') ' + second + '-'+ last;

Result:

console.log(formatted); // (123) 456-7890x4444

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM