美国电话号码格式为:
(XXX) XXX-XXXX对于长度为0 < length <= 10的任何给定字符串(仅数字),我希望获得匹配美国电话号码格式的所有可能块的数组。
例如:
Input: "54"
Output: ["(54", "54", "54)", "5) 4", "5-4"]对于更长的输入,输出将变得更加复杂,我认为手动键入它将是愚蠢的。
我想要做的是在我的项目中输入电话号码时,在搜索结果中突出显示它。
我使用https://www.npmjs.com/package/react-highlight-words来实现这一点--这个包可以接受searchWords数组来查找特定的文本。我找不到任何包或函数来帮助我完成这项任务,我也不太熟悉正则表达式(我甚至不确定它在这里是否有帮助)
发布于 2021-09-29 12:22:33
可以将数字字符串转换为正则表达式,该正则表达式查找一系列:可选的非数字(\D?),后跟目标数字,然后是可选的非数字。例如,"54"成为正则表达式\D?5\D?\D?4\D?。
如下所示:
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;
}这似乎起到了关键作用:
const numbers = [
"(321) 456-7890",
"(098) 765-4321",
"(541) 123-3456",
"(354) 123-3456",
"(335) 423-3456",
"(231) 541-1234",
"(231) 254-1234",
"(231) 225-4234",
"(231) 223-5434",
"(231) 223-3544",
"(231) 223-3454",
"(231) 543-3454",
];
const input = "54";
document.getElementById("output").innerHTML = `<div>
${numbers.map(num => "<div>" + format(num, input) + "</div>").join("")}
</div>`;
function format(num, digits) {
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;
}.highlight {
font-weight: bold;
color: red;
}<div id="output"></div>
https://stackoverflow.com/questions/69375819
复制相似问题