欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript實現(xiàn)的字符串replaceAll函數(shù)代碼分享

 更新時間:2023年06月14日 01:24:46   投稿:junjie  
這篇文章主要介紹了JavaScript實現(xiàn)的字符串replaceAll函數(shù)代碼分享,本文直接給出實現(xiàn)代碼,需要的朋友可以參考下

我們在Java中可以使用replaceAll()方法對字符串進(jìn)行批量替換,但在JS中replaceAll()方法是undefined,JS中只存在replace()方法,因此我們可以自己封裝JS中replaceAll()方法供我們便捷使用。

一、使用replace()方法進(jìn)行替換

定義一個字符串:

var str = "hello world";

使用replace()方法將字符串中的字母"l"替換成"i",原始做法:

?console.log(str.replace("l","i"));

輸出:

“heilo world”

需要執(zhí)行三次,非常不方便;

二、使用replaceAll()方法替換

封裝replaceAll()方法:

String.prototype.replaceAll = function(s1, s2) {
?? ?return this.replace(new RegExp(s1, "gm"), s2);
}

定義一個字符串:

var str = "hello world";

使用replaceAll()方法進(jìn)行批量替換:

console.log(str.replaceAll("l", "i"));

輸出:

“heiio worid”

只需要執(zhí)行一次,就完成了全部替換需求。

由于javascript中的replace函數(shù)無法替換全部匹配的字符串,所以需要為String類增加一個方法,代碼如下:

String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) {??
??? if (!RegExp.prototype.isPrototypeOf(reallyDo)) {??
??????? return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi": "g")), replaceWith);??
???? } else {??
??????? return this.replace(reallyDo, replaceWith);??
???? }??
}

到此這篇關(guān)于JavaScript實現(xiàn)的字符串replaceAll函數(shù)代碼分享的文章就介紹到這了,更多相關(guān)JavaScript replaceAll函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論