最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

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

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

定義一個(gè)字符串:

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

定義一個(gè)字符串:

var str = "hello world";

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

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

輸出:

“heiio worid”

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

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

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

相關(guān)文章

最新評(píng)論

瑞金市| 清新县| 云梦县| 西宁市| 西乌| 大荔县| 华池县| 岗巴县| 万州区| 德安县| 博客| 乐至县| 金湖县| 岫岩| 南漳县| 张家川| 新邵县| 体育| 禹城市| 门源| 清流县| 贡觉县| 林甸县| 盐边县| 顺平县| 内乡县| 梅州市| 连云港市| 罗城| 五大连池市| 吴川市| 威信县| 永德县| 贡觉县| 江孜县| 瑞丽市| 永平县| 云浮市| 衡山县| 平度市| 安吉县|