JS中实现replaceAll的方法
来源:互联网 发布:未经身份验证的网络 编辑:程序博客网 时间:2024/05/22 16:45
第一次发现JavaScript中replace()方法如果直接用str.replace("-","!")只会替换第一个匹配的字符.
而str.replace(/\-/g,"!")则可以全部替换掉匹配的字符(g为全局标志)。
replace()
Thereplace()methodreturnsthestringthatresultswhenyoureplacetextmatchingitsfirstargument
(aregularexpression)withthetextofthesecondargument(astring).
Iftheg(global)flagisnotsetintheregularexpressiondeclaration,thismethodreplacesonlythefirst
occurrenceofthepattern.Forexample,
vars="Hello.Regexpsarefun.";s=s.replace(/\./,"!");//replacefirstperiodwithanexclamationpointalert(s);
producesthestring“Hello!Regexpsarefun.”Includingthegflagwillcausetheinterpreterto
performaglobalreplace,findingandreplacingeverymatchingsubstring.Forexample,
vars="Hello.Regexpsarefun.";s=s.replace(/\./g,"!");//replaceallperiodswithexclamationpointsalert(s);
yieldsthisresult:“Hello!Regexpsarefun!”
所以可以用以下几种方式.:
string.replace(/reallyDo/g,replaceWith);
string.replace(newRegExp(reallyDo,'g'),replaceWith);
string:字符串表达式包含要替代的子字符串。
reallyDo:被搜索的子字符串。
replaceWith:用于替换的子字符串。
- <scripttype="text/javascript">
- String.prototype.replaceAll=function(reallyDo,replaceWith,ignoreCase){
- if(!RegExp.prototype.isPrototypeOf(reallyDo)){
- returnthis.replace(newRegExp(reallyDo,(ignoreCase?"gi":"g")),replaceWith);
- }else{
- returnthis.replace(reallyDo,replaceWith);
- }
- }
- </script>
原文 :http://fuleonardo.iteye.com/blog/339749
- JS中实现replaceAll的方法
- 在js中,实现replaceAll的方法
- JS中实现replaceAll的方法
- JS中实现replaceAll的方法
- JS中实现replaceAll的方法
- JS中实现replaceAll的方法
- JS中实现replaceAll的方法
- JS中实现replaceAll的方法
- JS中实现replaceAll的方法
- js中实现replaceAll方法
- 实现js的replaceAll方法
- 实现js的replaceAll方法
- 实现js的replaceAll方法
- js 实现ReplaceAll 的方法
- 实现js的replaceAll方法
- js 实现ReplaceAll 的方法
- js 实现ReplaceAll 的方法
- 实现js的replaceAll方法
- JS获取浏览器窗口大小
- 字母 日期或时间元素 表示 示例 (java)
- 正则表达式全部符号解释
- 验证字符串是否是日期格式(支持24小时制)
- Android多媒体开发【12】-- android中OpenMax的实现【3】OMX中主要成员
- JS中实现replaceAll的方法
- C#设计模式07-桥接模式
- jquery读写cookie
- maven + tomcat 热部署
- Spring + Kafka 客户端实现
- Nginx安装部署
- Linux查看CPU和内存使用情况
- 在Centos系统中搭建Hadoop集群
- linux下提示bash:command not found