JS的replace方法
from
http://www.cnblogs.com/mxw09/archive/2010/08/12/1797905.html
replace() 方法的参数 replacement 可以是函数而不是字符串。在这种情况下,每个匹配都调用该函数,它返回的字符串将作为替换文本使用。该函数的第一个参数是匹配模式的字符串。接下来的参数 是与模式中的子表达式匹配的字符串,可以有 0 个或多个这样的参数。接下来的参数是一个整数,声明了匹配在 stringObject 中出现的位置。最后一个参数是 stringObject 本身。
下文展示了几种javascript正则表示式的repalce方式,有些方式我们很少在别的地方看到,如第二种和第三方中方法。
//下面的例子用来获取url的两个参数,并返回urlRewrite之前的真实Url
var reg=new RegExp("(http://www.qidian.com/BookReader/)(\\d+),(\\d+).aspx","gmi");var url="http://www.qidian.com/BookReader/1017141,20361055.aspx";var rep=url.replace(reg,"$1ShowBook.aspx?bookId=$2&chapterId=$3");alert(rep);
var rep2=url.replace(reg,function(m,p1,p2,p3){return p1+"ShowBook.aspx?bookId="+p3+"&chapterId="+p3});alert(rep2);var rep3=url.replace(reg,function(){var args=arguments; return args[1]+"ShowBook.aspx?bookId="+args[2]+"&chapterId="+args[3];});alert(rep3);var bookId;var chapterId;function capText(){ var args=arguments; bookId=args[2]; chapterId=args[3]; return args[1]+"ShowBook.aspx?bookId="+args[2]+"&chapterId="+args[3];}var rep4=url.replace(reg,capText);alert(rep4);alert(bookId);alert(chapterId);var reg2=new RegExp("(http://www.qidian.com/BookReader/)(\\d+),(\\d+).aspx","gmi");var m=reg2.exec("http://www.qidian.com/BookReader/1017141,20361055.aspx");var s="";for (i = 0; i < m.length; i++) { s = s + m[i] + "\n"; }alert(s);bookId=m[2];chapterId=m[3];alert(bookId);alert(chapterId);var reg3=new RegExp("(http://www.qidian.com/BookReader/)(\\d+),(\\d+).aspx","gmi");reg3.test("http://www.qidian.com/BookReader/1017141,20361055.aspx");//获取三个分组alert(RegExp.$1);alert(RegExp.$2);alert(RegExp.$3);var strM = "javascript is a good script language";alert(strM.replace(/(javascript)\s*(is)/g,"$1 $2 fun. it $2"));
var strM = "javascript is a good script language";function change(word){ return word.indexOf(0).toUpperCase()+word.substring(1);}alert(strM.replace(/\b\w+\b/g,change));var strM = "javascript is a good script language";function change(word){ var result = word.match(/(\w)/g);if ( result ){ var str = ""; for ( var i=result.length-1; i>=0; i-- ) { str += result; } return str;}else{ return "null";}}alert(strM.replace(/\b(\w)+\b/g,change));