详解javascript replace高级用法(2)

<script> /*要求:将下列字符串中的所有首字母大写*/ var str = "Tomorrow may not be better, but better tomorrow will surely come!"; var newStr = str.replace(/\b\w+\b/gi,function (matchStr){ console.log(matchStr);//匹配到的字符 return matchStr.substr(0,1).toUpperCase() + matchStr.substr(1); }); console.log(newStr); </script>

3.3、参数二为函数之绑定数据----artTemplate模板核心

<h1>周星驰喜剧电影:</h1> <div></div> <script type="text/javascript"> var data = { name: "功夫", protagonist: "周星驰" }, domStr = '<div><span>名称:</span><span>{{name}}</span></div><div><span>导演:</span><span>{{protagonist}}</span> </div>'; document.getElementById("content").innerHTML = formatString(domStr,data); /*绑定数据的核心就是使用正则进行匹配*/ function formatString(str,data){ return str.replace(/{{(\w+)}}/g,function (matchingStr,group1){ return data[group1]; }); } </script>

4、replace高级用法之获取与正则表达式匹配的文本

4.1、replace高级用法之获取与正则表达式进行匹配的源字符串

<script> var str = "i am a good man"; var newStr = str.replace(/good/g,"$&"); console.log(newStr);//结果:输出i am a good man /*解释:在这里”$&”就是与正则表达式进行匹配的那个源字符串*/ </script>

4.2、replace高级用法之获取正则表达式匹配到的字符

<script> /*要求:将"i am a good man"替换成"i am a good-gond man" */ var str = "i am a good man"; var newStr = str.replace(/good/g,"$&-$&"); console.log(newStr); /*解释:在这里”$&”可以获取到前面正则表达式匹配的内容,如上面的”$&”就是正则表达式匹配到的”good”*/ </script>

5、replace高级用法之获取正则匹配的左边的字符

<script> /*要求:将下列字符串替换成"java-java is a good script"*/ var str = "javascript is a good script"; var newStr = str.replace(/script/,"-$`"); console.log(newStr) /*解释:"$`"获取的是正则左边的内容,如上正则中"script"字符前面的是"java","-$`"就是"-java","-$`"会把script替换掉。*/ </script>

6、replace高级用法之获取正则匹配的右边的字

<script> /*要求:将下列字符替换成"java is a good language!it is a good script is a good script"*/ var str = "javascript is a good script"; var newStr = str.replace(/script/," is a good language!it$'"); console.log(newStr) /*解释:"$'"获取的就是str右边的内容,如上正则中"$'"就是" is a good script"。 " is a good language!it$'"会把正则匹配到的"script"替换掉*/ </script>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/80a9e962a052b7633bd47cf545843794.html