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

Javascript
阻止JavaScript事件冒泡传递(cancelBubble 、stopPropagation)
(转载)JavaScript中匿名函数,函数直接量和闭包
简单的无缝滚动程序-仅几行代码
Javascript中的数学函数集合
javascript之大字符串的连接的StringBuffer 类
javascript之对系统的toFixed()方法的修正
用javascript实现自定义标签
js在客户端验证密码强度,兼容FireFox和IE
javascript背景颜色按时变换
脚本分析、压缩、混淆工具 JSA新版本发布,压缩效率提高大约10%
javascript语句中的CDATA标签的意义
用javascript实现分割提取页面所需内容
网上抓的一个特效
js之点击 超连接,提示一个层.点击空白.层消失
模拟用户操作Input元素,不会触发相应事件
弹出广告特效代码(一个IP只弹出一次)
(仅IE下有效)关于checkbox 三态
JavaScript Archive Network 集合
关于__defineGetter__ 和__defineSetter__的说明
textContent在Firefox下与innerText等效的属性

Javascript 中的 JavaScript 中的replace方法说明


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 68 ::
收藏到网摘: 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!”