- 0133技术站
- 联系QQ:18840023
- QQ交流群
- 微信公众号
replace()方法查找正则表达式和字符串之间的匹配项,并使用新的子字符串替换匹配的子字符串。
替换字符串可包括以下特殊替换模式:
Sr.No | 模式和插入 |
---|---|
1 | $$ 插入"$"。 |
2 | $& 插入匹配的子字符串。 |
3 | $` 插入匹配子字符串之前的字符串部分。 |
4 | $' 插入匹配子字符串后面的字符串部分。 |
5 | $n or $nn 如果n或nn是十进制数字,则插入第n个带括号的子匹配字符串,前提是第一个参数是RegExp对象。 |
语法:
string.replace(regexp/substr, newSubStr/function[, flags]);
参数:
● regexp - 一个RegExp对象。匹配由参数#2的返回值替换。
● substr - 要由newSubStr替换的String。
● newSubStr - 替换从参数#1接收的子字符串的String。
● function - 要调用以创建新子字符串的函数。
● flags - 包含RegExp标志的任意组合的String:g。
返回值:
它只返回一个新的更改字符串。
例1:
var re = /apples/gi; var str = "Apples are round, and apples are juicy."; var newstr = str.replace(re, "oranges"); console.log(newstr)
输出:
oranges are round, and oranges are juicy.
例2:
var re = /(\w+)\s(\w+)/; var str = "zara ali"; var newstr = str.replace(re, "$2, $1"); console.log(newstr);
输出:
ali, zara
推荐手册