当前位置: 首页 > 图文教程 > 网络编程 > Javascript > JavaScript 中的replace方法说明

Javascript
JavaScript实现Sleep函数的代码
一个可以显示阴历的JS代码
从csdn弄下来的页面预先载入效果
键盘事件中keyCode、which和charCode 的兼容性测试
一个支持ff的modaldialog的js代码
[js+css]点击隐藏层,点击另外层不能隐藏原层
用javascript实现页面打印的三种方法
HTML-CSS群中单选引发的“事件”
一款不错的键盘密码输入js程序
限制文本字节数js代码
静态图片的十一种滤镜效果--不支持Ie7及非IE浏览器。
用javascript动态调整iframe高度的方法
用一段js程序来实现动画功能
javascript实现划词标记+划词搜索功能
javascript 简单高效判断数据类型 系列函数 By shawl.qiu
服务端 VBScript 与 JScript 几个相同特性的写法 By shawl.qiu
禁止F5等快捷键的JS代码
在textarea文本域中显示HTML代码的方法
Javascript之文件操作
修改发贴的编辑功能

Javascript 中的 JavaScript 中的replace方法说明


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 63 ::
收藏到网摘: n/a

第一次发现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!”