2017-05-29 106 views
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]它仅捕获图案的第一次出现,从而通过匹配阵列循环将是无用的。有没有办法让匹配数组保持每场匹配?任何帮助不胜感激。

回答

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); 
}); 
+0

用'replaceAll'替换'replace',它的功能非常完美!谢谢。 – Tony

+0

@Tony:刷新页面,你会明白'replaceAll'方法不是有用的*(因为它只是模式中的一个标志)* –

+0

替换不适用于我,我得到'replace is not defined' – Tony