2015-10-26 49 views
-3

CODE:正則表達式或jquery的替換所有字符串匹配在另一個字符串

var searchedTerm = "test"; 
var returnedString = "National testing Plant testers"; 
var replacedString = returnedString.replace(/\searchedTerm/g, '<span class="highlight">'+searchedTerm+'</span>'); 

換句話說更換搜索的字符串,從返回更長的字符串後,我要突出的地方搜索字符串匹配返回一個。請記住突出顯示它是否在同一個返回的字符串(又名全局)中多次匹配。

+0

像這樣的事情? http://stackoverflow.com/questions/31275446/how-to-wrap-part-of-a-text-in-a-node-with-javascript – nhahtdh

+0

使用'RegExp'構造函數,'var regex = new RegExp(searledTerm , 'G'); var replacedString = returnedString.replace(regex,''+ searchingTerm +''); ' – Tushar

回答

1

使用RegExp()轉換搜索字符串正則表達式

var searchedTerm = "test"; 
 
var returnedString = "National testing Plant testers"; 
 
var replacedString = returnedString.replace(new RegExp(searchedTerm, 'g'), '<span class="highlight">' + searchedTerm + '</span>'); 
 

 
document.write(replacedString);
.highlight { 
 
    color: red; 
 
}