Regex环路和号码电话



这是我的代码,但我无法显示其他数字,因为我已经索引了[0],我不知道如何显示其他数字。

Example string: "Hello, you can contact me at 0744224422 or 0192234422."
Result code : "Hello, you can contact me at <span>0744224422</span> or <span>0744224422</span>."

在这个例子中:我的代码将替换";0192234422";通过0744224422";这是逻辑";但我希望它显示0192234422…我该怎么做?

感谢

let selector = document.querySelectorAll('.message > div > .chat');
for (let index = 0; index < selector.length; index++) {
if (selector[index].innerText) {
let text = selector[index].innerText;
const regex = /(d[s-]?)?[([s-]{0,2}?d{3}[)]s-]{0,2}?d{3}[s-]?d{4}/gim;
if (text.match(regex).length) {
const newTexte = ` <span>${text.match(regex)[0].trim()}</span> `;
selector[index].innerHTML = text.replace(regex, newTexte); 
};
}
}

如果使用replace函数的$替换字符,它将在其中放置正确的文本。而不是trim,只需在正则表达式的非空白部分周围放上括号,就可以有效地让捕获组成为修剪操作。

let selector = document.querySelectorAll('.message > div > .chat');
for (let index = 0; index < selector.length; index++) {
if (selector[index].innerText) {
let text = selector[index].innerText;
const regex = /(d[s-]?)?([([s-]{0,2}?d{3}[)]s-]{0,2}?d{3}[s-]?d{4})/gim;
if (text.match(regex).length) {
const newTexte = ` <span class="red">$2</span> `;
selector[index].innerHTML = text.replace(regex, newTexte); 
};
}
}
.red {
background: yellow
}
<div class="message">
<div>
<div class="chat">Hello, you can contact me at 0744224422 or 0192234422.</div>
</div>
</div>

我将尝试提请注意以下正则表达式中的差异:(因为我添加了一组括号(

/(\d[\s-]?(?[\(\[\s-]{0,2}?\d{3}[\(\]]\s-]{0,1}?\d{3}[\s-]?\d{4}/gim((/(\d[\s-]?(?([\(\[\s-]{0,2}?\d{3}[\(\]\s-]{0.2}?\d{3}[\s-]?\d{4}(/gim

您有两个独立的选择器实例吗?如果不是,则selector.length仅为1,这就是为什么只显示第一个数字的原因。您可以编辑html以拥有多个选择器实例(并使用display:inline进行样式设置,这样它就不会换行到新行上(EX:

let selector = document.querySelectorAll('.message > div > .chat');
for (let index = 0; index < selector.length; index++) {
if (selector[index].innerText) {
let text = selector[index].innerText;
const regex = /(d[s-]?)?[([s-]{0,2}?d{3}[)]s-]{0,2}?d{3}[s-]?d{4}/gim;
if (text.match(regex).length) {
const newTexte = ` <span>${text.match(regex)[0].trim()}</span> `;
selector[index].innerHTML = text.replace(regex, newTexte); 
};
}
}
<div class="message">
<div>
<p class="chat" style="display:inline">
Hello, you can contact me at 0744224422 or </p>
<p class="chat" style="display:inline">0192234422</p>
<!-- add more numbers as needed in another <p class="chat" style="display:inline" ></p>-->
</div>
</div>

谢谢你的回答,但当电话号码写在字符串中时,我只想添加一个<span></span>(或更多(。。

最新更新