繁体   English   中英

正则表达式循环和电话号码

[英]Regex loop and number phone

这是我的代码,但我无法显示其他数字,因为我已将 [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); 
            };
        }
    }

如果您使用替换功能的$替换字符,它将在那里放置正确的文本。 而不是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,2}?\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> (或更多)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM