var value = '78005553535';
var regex = /(\d{1})(\d{3})(\d{3})(\d{2})(\d{2})/;
var mask = '+$1 ($2) $3-$4-$5';
const countryCode = value.slice(0, 1);
const regionCode = value.slice(1, 4);
const partOne = value.slice(4, 7);
const partTwo = value.slice(7, 9);
const partThree = value.slice(9, 11);
strOut = `+${countryCode} (${regionCode}) ${partOne}-${partTwo}-${partThree}`;
strOut = value.replace(regex, mask);
strOut = value.replace(/(\d{1})(\d{3})(\d{3})(\d{2})(\d{2})/, mask);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Slice | |
Replace compile | |
Replace inline |
Test name | Executions per second |
---|---|
Slice | 1671550.9 Ops/sec |
Replace compile | 980714.1 Ops/sec |
Replace inline | 1035687.8 Ops/sec |
Benchmark Overview
The provided benchmark, "Performance formatted phone number. Regex replace vs slice. Ver. 2", tests the performance of two approaches to format a phone number: using regular expressions (Regex) and using the slice()
method.
Approaches Compared
slice()
method to extract parts of the phone number string and then concatenates them to form the formatted phone number.replace()
method) to replace the original phone number string with the formatted one.Pros and Cons of Each Approach
slice()
since it compiles the regular expression once and reuses it for each execution.Library Used
None are explicitly mentioned in the benchmark definition or test cases.
Special JS Features/Syntax
No special JavaScript features or syntax are used beyond what is standard for browser JavaScript execution.
Benchmark Preparation Code Explanation
The preparation code for this benchmark consists of:
var value = '78005553535'; // Phone number to be formatted
var regex = /(\\d{1})(\\d{3})(\\d{3})(\\d{2})(\\d{2})/; // Compiled regular expression
var mask = '+$1 ($2) $3-$4-$5'; // Replacement string
The slice()
method is used to extract the individual parts of the phone number:
const countryCode = value.slice(0, 1);
const regionCode = value.slice(1, 4);
const partOne = value.slice(4, 7);
const partTwo = value.slice(7, 9);
const partThree = value.slice(9, 11);
The formatted phone number is then constructed using the slice()
method:
strOut = `+${countryCode} (${regionCode}) ${partOne}-${partTwo}-${partThree}`;
Alternative Approaches
Other approaches that could be used to format a phone number include:
const strOut = `+${value.slice(0, 1)} (${value.slice(1, 4)}) ${value.slice(4, 7)}-${value.slice(7, 9)}-${value.slice(9, 11)}`;
const moment = require('moment');
const formattedPhoneNumber = moment(value).format('+ (XXX) XXX-XX-XX');
const strOut = value.replace(/^(\d{1})(\d{3})(\d{3})(\d{2})(\d{2})$/, '+$1 ($2) $3-$4-$5');
Note that these alternative approaches may have different performance characteristics and requirements than the original approach used in the benchmark.