JavaScript 中的replace方法说明
更新时间:2007年04月13日 00:00:00 作者:
第一次发现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!”
相关文章
ionic进入多级目录后隐藏底部导航栏(tabs)的完美解决方案
这篇文章主要介绍了ionic进入多级目录后隐藏底部导航栏(tabs)的完美解决方案,在文章中用到了angularjs的指令知识点,对ionic隐藏底部导航栏知识感兴趣的朋友一起学习吧2016-11-11javascript中alert()与console.log()的区别
我们在做js调试的时候使用 alert 可以显示信息,调试程序,alert 弹出窗口会中断程序, 如果要在循环中显示信息,手点击关闭窗口都累死。而且 alert 显示对象永远显示为[object ]。 自己写的 log 虽然可以显示一些 object 信息,但很多功能支持都没有 console 好2015-08-08JavaScript设计模式之构造器模式(生成器模式)定义与用法实例分析
这篇文章主要介绍了JavaScript设计模式之构造器模式(生成器模式)定义与用法,结合实例形式分析了javascript构造器模式的概念、原理、与工厂模式的区别以及相关使用方法,需要的朋友可以参考下2018-07-07
最新评论