JS利用正则配合replace替换指定字符
定义和用法 复制代码 代码如下: <script type="text/javascript"> var str="Visit Microsoft!" document.write(str.replace(/Microsoft/,"W3School")) </script> 输出: Visit W3School! 例子 2 在本例中,我们将执行一次全局替换,每当 "Microsoft" 被找到,它就被替换为 "W3School": 复制代码 代码如下: <script type="text/javascript"> var str="Welcome to Microsoft! " str=str + "We are proud to announce that Microsoft has " str=str + "one of the largest Web Developers sites in the world." document.write(str.replace(/Microsoft/g,"W3School")) </script> 输出: Welcome to W3School! We are proud to announce that W3School has one of the largest Web Developers sites in the world. 例子 3 您可以使用本例提供的代码来确保匹配字符串大写字符的正确: 复制代码 代码如下: text = "javascript Tutorial"; text.replace(/javascript/i,"JavaScript"); 例子 4 在本例中,我们将把 "Doe,John" 转换为 "John Doe" 的形式: 复制代码 代码如下: name = "Doe,John"; name.replace(/(w+)s*,s*(w+)/,"$2 $1"); 例子 5 在本例中,我们将把所有的花引号替换为直引号: 复制代码 代码如下: name = '"a","b"'; name.replace(/"([^"]*)"/g,"'$1'"); 例子 6 在本例中,我们将把字符串中所有单词的首字母都转换为大写: 复制代码 代码如下: name = 'aaa bbb ccc'; uw=name.replace(/bw+b/g,function(word){ return word.substring(0,1).toUpperCase()+word.substring(1);} ); 例子 7 复制代码 代码如下: var str="fsaf$a$assdfdasfa$a$dsfadsf"; var strr='$'+'a'+'$'; var name = '"a","b"'; var reger=new RegExp("[$]a[$]","gm"); alert(str.replace(reger,'555888')); PS:这里再为大家提供一款功能强大的在线正则工具供大家使用: JavaScript正则表达式在线测试工具: http://tools.aspzz.cn/regex/javascript 正则表达式在线生成工具: http://tools.aspzz.cn/regex/create_reg (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |