2017-05-29 272 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