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

JS中實(shí)現(xiàn)replaceAll的方法(實(shí)例代碼)

 更新時(shí)間:2023年06月14日 01:04:12   投稿:jingxian  
本文是對JS中實(shí)現(xiàn)replaceAll的方法進(jìn)行了詳細(xì)的總結(jié)介紹,需要的朋友可以過來參考下,希望對大家有所幫助

我們在Java中可以使用replaceAll()方法對字符串進(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í)行一次,就完成了全部替換需求。

補(bǔ)充

第一次發(fā)現(xiàn)JavaScript中replace() 方法如果直接用str.replace("-","!") 只會(huì)替換第一個(gè)匹配的字符.
而str.replace(/\-/g,"!")則可以全部替換掉匹配的字符(g為全局標(biāo)志)。

replace()

The replace() method returns the string that results when you replace text matching its first argument
(a regular expression) with the text of the second argument (a string).
If the g (global) flag is not set in the regular expression declaration, this method replaces only the first
occurrence of the pattern. For example,

var s = "Hello. Regexps are fun.";s = s.replace(/\./, "!"); // replace first period with an exclamation pointalert(s);

produces the string “Hello! Regexps are fun.” Including the g flag will cause the interpreter to
perform a global replace, finding and replacing every matching substring. For example,

var s = "Hello. Regexps are fun.";s = s.replace(/\./g, "!"); // replace all periods with exclamation pointsalert(s);

yields this result: “Hello! Regexps are fun!”

所以可以用以下幾種方式.:

string.replace(/reallyDo/g, replaceWith);
string.replace(new RegExp(reallyDo, 'g'), replaceWith);

string:字符串表達(dá)式包含要替代的子字符串。
reallyDo:被搜索的子字符串。
replaceWith:用于替換的子字符串。

<script type="text/javascript">?
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);?
??? }?
}?
</script>?

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

相關(guān)文章

最新評論

泗阳县| 西林县| 通州市| 石台县| 文水县| 天水市| 莆田市| 南投市| 祥云县| 股票| 通城县| 和静县| 肥乡县| 莒南县| 六盘水市| 河间市| 镶黄旗| 林甸县| 邹城市| 大姚县| 保亭| 汾西县| 睢宁县| 和林格尔县| 平乐县| 忻城县| 吉安市| 福清市| 荔波县| 宁陕县| 吉首市| 鄂伦春自治旗| 佛冈县| 岱山县| 綦江县| 焦作市| 平遥县| 阳山县| 彭阳县| 宁津县| 崇州市|