RegExp 正則匹配一句話,其中一個單詞顯示高亮

效果圖:

<script type="text/javascript">

var str1 = 'For months, city has been engulfed in widespread violence and mobs attacksp the ';

var result1 = reg_replace(str1, "the");

console.log(result1);

function reg_replace(str, keyword) {

var reg = new RegExp(keyword, "gi");

var result = [];

var match_result = str.split(reg);

if (match_result.length > 1) {

for (var i = 0, length = match_result.length; i < length; i++) {

if (i) {

result.push(keyword);

}

result.push(match_result[i]);

}

} else {

match_result.unshift('');

//push('');

match_result.push('');

 

result = match_result;

}

 

return result;

console.log(result)

}

</script>

 

小程序中:

發佈了46 篇原創文章 · 獲贊 21 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章