当JavaScript中的搜索词为234时,有人可以帮我将手机号码突出显示为(1 23 ) 4 56-7890吗?
我有一个这种格式的电话号码(123)456-7890,我需要根据搜索词突出显示该电话号码,以便使其看起来像这样(1 23 ) 4 56-7890(如果搜索词为234
。
const phoneNumber = "(123) 456-7890";
phoneNumber.replace("123","<strong>123</strong>")
这仅适用于连续3个数字,并且出现特殊字符问题
答案 0 :(得分:0)
字符串替换可能无法动态替换不同的搜索词。以下将根据需要生成一个字符串
const phone = "(123) 456-7823";
const search = "234".split(""); // change the search term to whatever
// this format the search char to strong,
let formatted = phone.split("").map( c => {
let index = search.indexOf(c);
if( index !== -1){
search.splice(index, 1);
return `<strong>${c}</strong>`
} else return c;
}); // an array
// join formatted to become a string
console.log(formatted.join(''));
// display html
var x = document.getElementById("demo");
x.innerHTML = formatted.join('');
<p id="demo"></p>