js替換字符串中所有指定的字符(實(shí)現(xiàn)代碼)
第一次發(fā)現(xiàn)JavaScript中replace() 方法如果直接用str.replace("-","!") 只會替換第一個匹配的字符.
而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:用于替換的子字符串。
Js代碼
<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>
以上這篇js替換字符串中所有指定的字符(實(shí)現(xiàn)代碼)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
nodejs讀取本地中文json文件出現(xiàn)亂碼解決方法
在本篇文章中我們給大家分享了關(guān)于nodejs讀取本地中文json文件出現(xiàn)亂碼的解決方法,需要的朋友們可以學(xué)習(xí)下。2018-10-10javascript排序函數(shù)實(shí)現(xiàn)數(shù)字排序
這篇文章主要介紹了javascript排序函數(shù)實(shí)現(xiàn)數(shù)字排序的相關(guān)資料,附上示例,需要的朋友可以參考下2015-06-06詳解JS中continue關(guān)鍵字和break關(guān)鍵字的區(qū)別
在javascript中continue的作用是退出當(dāng)前次循環(huán),break的作用則是一旦當(dāng)前循環(huán)有break那么直接退出整個循環(huán)。本文將通過一些示例為大家詳細(xì)講講二者的區(qū)別,感興趣的可以了解一下2022-08-08使用Angular和Nodejs、socket.io搭建聊天室及多人聊天室
本文主要給大家詳細(xì)介紹Angular和Nodejs、socket.io的使用,以及如何使用Angular和Nodejs、socket.io搭建聊天室及多人聊天室,需要的朋友可以來參考下2015-08-08uniapp中uni.request(OBJECT)接口請求封裝實(shí)例代碼
在開發(fā)的時候經(jīng)常會用到前端請求后端接口,每次的請求都會出現(xiàn)地址不一樣,參數(shù)不一樣,方式不一樣等等情況,下面這篇文章主要給大家介紹了關(guān)于uniapp中uni.request(OBJECT)接口請求封裝的相關(guān)資料,需要的朋友可以參考下2022-12-12

使用Microsoft Ajax Minifier減小JavaScript文件大小的方法