The US phone number format is:
(XXX) XXX-XXXX
For any given string (only digits) of length 0 < length <= 10
I want to get array of all possible chunks matching US phone number format.
For example:
Input: "54"
Output: ["(54", "54", "54)", "5) 4", "5-4"]
For longer Input the Output is going to be much more complicated, and I think it would be stupid to type it by hand.
What I'm trying to do is to highlight phone number in a search result as I type it in my project.
I am using the https://www.npmjs.com/package/react-highlight-words to achieve that - this package can take the array of searchWords
to look for in specific text. I can't find any package or function to help me accomplish this task, neither I am fluent with regex (I'm not even sure whether it would help here)
CodePudding user response:
You can convert your digits string into a regular expression that look for a series of: an optional non-digit (\D?
) followed by the target digit followed by an optional non-digit. For instance, "54"
becomes the regular expression \D?5\D?\D?4\D?
.
Like this:
function format(num, digits) {
// Since we're using a template literal, we have to escape the backslash
// in `\D` for the regex constructor to see it
const rex = new RegExp([...digits].map(digit => `\\D?${digit}\\D?`).join(""), "g");
const result = num.replace(rex, m => `<span class="highlight">${m}</span>`);
return result;
}
That seems to do the trick: