javascript中使用replaceAll()函数实现字符替换的方法


而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!”
所以可以用以下几种方式.:
string.replace(/reallyDo/g, replaceWith);
string.replace(new RegExp(reallyDo, 'g'), replaceWith);
string:字符串表达式包含要替代的子字符串。
reallyDo:被搜索的子字符串。
replaceWith:用于替换的子字符串。

复制代码 代码如下:

<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>



相关阅读:
通用分页存储过程,源码共享,大家共同完善
phpcms图片频道模板制作
认识Oracle 11g R1中密码大小写敏感
用php制作友好的404错误页面
Windows 2003如何迁移到Windows 2008
微软官方网站专设辨别真伪版块判断Win7是否盗版
Linux 系统硬盘 优化
IIS服务器组建攻略
JavaScript常用对象的方法和属性小结
不能通过mysql.sock连接MySQL问题的方法
Asp.Net的Life Cycle原来如此重要
HTML的全局架构标签
SQL Server 2008的升级和部署问题
配置 SQLServer2005 以允许远程连接
快速导航

Copyright © 2016 phpStudy |