1
所以我目前的HTML看起来像Javascript匹配字符串中的多个匹配项?
<p class="comment-post-text">@333<br /> @44<br />@564</p>
我试图建立这样
@333 @44 @564
链接但是我的结果是
@333 @333 @333
和我使用正则表达式来验证一个数字是否在@
符号之后,将文本转换为链接并链接回下一篇文章的散列。这是一个或多或少的报价系统。我的问题是,它似乎只匹配我的正则表达式的第一次出现,而不是匹配每个事件。
$('.comment-post-text').each(function(index) {
let text = $(this).text();
let matches = text.match(/@(\d+)/);
if(matches !== null){
console.log(matches);
let newText = replaceAll(text, /@(\d+)/, "<a href = '#pi_" + matches[1] + "'>" + matches[0] + "</a><br/>");
$(this).replaceWith(newText);
}
});
function replaceAll(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
}
的问题是发生在这里matches[1]
它仅捕获图案的第一次出现,从而通过匹配阵列循环将是无用的。有没有办法让匹配数组保持每场匹配?任何帮助不胜感激。
用'replaceAll'替换'replace',它的功能非常完美!谢谢。 – Tony
@Tony:刷新页面,你会明白'replaceAll'方法不是有用的*(因为它只是模式中的一个标志)* –
替换不适用于我,我得到'replace is not defined' – Tony