Javascript匹配字符串中的多个匹配项?

时间:2017-05-29 23:21:14

标签: javascript jquery html regex

所以我当前的HTML看起来像

<p class="comment-post-text">@333<br /> @44<br />@564</p>

我试图创建看起来像

的链接
@333 @44 @564

但是我的结果是

@333 @333 @333

我正在使用Regex来验证如果一个数字出现在@符号之后,将文本转换为链接并链接回下一篇文章的哈希值。它或多或少是一个引用系统。我的问题是它似乎只匹配我的正则表达式的第一次出现,而不是匹配每次出现。

$('.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],它只捕获模式的第一次出现,因此循环匹配数组将是无用的。有没有办法让匹配数组保持匹配的每次出现?任何帮助非常感谢。

1 个答案:

答案 0 :(得分:1)

您无需使用String.prototype.match方法检查是否有要替换的内容。直接使用String.prototype.replace方法,对替换字符串中的第一个捕获组$1和整个匹配$&进行反向引用。

$('.comment-post-text').each(function( index ) {
    let text = $( this ).text();
    let newText = text.replace(/@(\d+)/g, "<a href = '#pi_$1'>$&</a><br/>");
    $(this).replaceWith(newText);
});