JavaScript 中的replace方法說明
更新時間:2007年04月13日 00:00:00 作者:
第一次發(fā)現(xiàn)JavaScript中replace() 方法如果直接用str.replace("-","!") 只會替換第一個匹配的字符.
而str.replace(/\-/g,"!")則可以替換掉全部匹配的字符(g為全局標志)。
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!”
而str.replace(/\-/g,"!")則可以替換掉全部匹配的字符(g為全局標志)。
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!”
相關文章
javascript動態(tài)分頁的實現(xiàn)方法實例
最近的項目需要添加一個分頁導航的功能,沒有用網(wǎng)上封裝好的文件,通過JS自己簡單實現(xiàn)了效果,這篇文章主要給大家介紹了關于javascript動態(tài)分頁的實現(xiàn)方法,需要的朋友可以參考下2022-06-06JS實現(xiàn)求數(shù)組起始項到終止項之和的方法【基于數(shù)組擴展函數(shù)】
這篇文章主要介紹了JS實現(xiàn)求數(shù)組起始項到終止項之和的方法,基于數(shù)組擴展函數(shù)實現(xiàn)該功能,涉及javascript針對數(shù)組的簡單判斷、遍歷等相關操作技巧,需要的朋友可以參考下2017-06-06微信小程序?qū)崿F(xiàn)密碼顯示與隱藏的睜眼閉眼功能
這篇文章主要介紹了微信小程序?qū)崿F(xiàn)密碼顯示與隱藏的睜眼閉眼功能,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧2023-02-02ionic進入多級目錄后隱藏底部導航欄(tabs)的完美解決方案
這篇文章主要介紹了ionic進入多級目錄后隱藏底部導航欄(tabs)的完美解決方案,在文章中用到了angularjs的指令知識點,對ionic隱藏底部導航欄知識感興趣的朋友一起學習吧2016-11-11javascript中alert()與console.log()的區(qū)別
我們在做js調(diào)試的時候使用 alert 可以顯示信息,調(diào)試程序,alert 彈出窗口會中斷程序, 如果要在循環(huán)中顯示信息,手點擊關閉窗口都累死。而且 alert 顯示對象永遠顯示為[object ]。 自己寫的 log 雖然可以顯示一些 object 信息,但很多功能支持都沒有 console 好2015-08-08JavaScript設計模式之構(gòu)造器模式(生成器模式)定義與用法實例分析
這篇文章主要介紹了JavaScript設計模式之構(gòu)造器模式(生成器模式)定義與用法,結(jié)合實例形式分析了javascript構(gòu)造器模式的概念、原理、與工廠模式的區(qū)別以及相關使用方法,需要的朋友可以參考下2018-07-07微信小程序?qū)崿F(xiàn)商品屬性聯(lián)動選擇
這篇文章主要為大家詳細介紹了微信小程序?qū)崿F(xiàn)商品屬性聯(lián)動選擇,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-02-02