正则_二
<h3>replace</h3>
<p>功能:str.replace(/a/g,"*") 所有的a用*来替换</p>
<script> var str = "abcdeafghiajkamsna"; var i = 0; var result = str.replace(/a/g, function(res){ //res对应匹配规则匹配的元素 i++; return res; }) </script> <script> var str1 = "88452489"; var arr1 = ["零","一","二","三","四","五","六","七","八","九"]; var result1 = str1.replace(/\d/g, function(){ //三个参数 arguments[0],arguments[1],arguments[2] input[index] index input //当前匹配的字符串 //当前匹配的索引 //当前匹配的总的对象 return arr1[arguments[0]]; }) </script> <script> var str2 = "My name is {0}. I am {1} years old. I am in class {2} grade {3}."; var arr2 = ["刘先坤", 16, 3, 5]; var reg2 = /{(\d+)}/g; var result2 = str2.replace(reg2, function(){ arguments[1] return arr2[arguments[1]]; }); </script> <script> var reg3 = /<div>.+<\/div>/; reg3.exec(document.body.innerHTML); </script> <script> var str4 = "我是{{name}},年龄{{age}},性别{{sex}}"; var data = {name:"姓名", age: 18}; render(str4, data); function render(str, data){ var reg = /{{(.+?)}}/g; var str2 = str.replace(reg, function(){ return data[arguments[1]]; }); return str2; } </script>