javascript replace函数
2014年8月11日 20:39
定义
replace()函数用于替换字符串.
语法
1 | stringObject.replace(regexp/substr, newSubStr/ function ) |
参数
regexp/substr 正则表达式/字符串
newSubStr/function 替换文本/生成替换文本的函数
示例
1 2 | var str = "Visit Microsoft!" ; var res = str.replace( "Microsoft" , "W3Schools" ); |
替换字符
假如替换字符newSubStr中包含$符号,它表示什么?
$1、 $2、 ...、$99 与 regexp 中的第1到第99个子表达式相匹配的文本
$& 与 regexp 相匹配的子串
$` 位于匹配子串左侧的文本
$' 位于匹配子串右侧的文本
$$ 直接量符号。
上面$1、$2...中提到的子表达式是什么意思?正则表达式中用小括号包裹起来的表达式.
例如:
/a/ 无子表达式
/[a]/ 无子表达式
/(a)/ 有子表达式(a)
/(a), (b)/ 有子表达式(a)、(b)
示例
1 2 3 | name = "Doe, John" ; name.replace(/(\w+)\s*, \s*(\w+)/, "$2 $1" ); //输出"John Doe" |
替换函数
替换函数说明
1 | function (match, p1, p2,..., offset, string) |
match 匹配到的字符串
p1, p2... 匹配到的子表达式
offset 匹配到字符串的位置
string 整个字符串
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | var name = "ace:mm-Abc" .replace(/([\:\-\_]+(.))/, function (match, p1, p2, offset, total){ console.log( "match:" + _); console.log( "p1:" + separator); console.log( "p2:" + letter); console.log( "offset:" + offset); console.log( "total:" + total) return offset ? p2.toUpperCase() : p2; }) console.log(name) /*输出 substr::m test.html:43 p1::m p2:m offset:3 total:ace:mm-Abc aceMm-Abc */ |
上面正则表达式中有两个子表达式
p1是子表达式([\:\-\_]+(.))匹配到的内容":m"
p2是子表单是(.)匹配到的内容"m"