这篇文章主要为大家详细介绍了javascript中replace的使用方法,使用replace和正则表达式共同实现字符串trim方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
ECMAScript提供了replace()方法。这个方法接收两个参数,第一个参数可以是一个RegExp对象或者一个字符串,第二个参数可以是一个字符串或者一个函数。现在我们来详细讲解可能出现的几种情况。
1. 两个参数都为字符串的情况
1
2
3
4
5
|
var
text =
'cat, bat, sat, fat'
;
// 在字符串中找到at,并将at替换为ond,只替换一次
var
result = text.replace(
'at'
,
'ond'
);
// "cond, bat, sat, fat"
console.log(result);
|
2. 第一个参数为RegExp对象,第二个参数为字符串
我们可以发现上面这种情况只替换了第一个at,如果想要替换全部at,就必须使用RegExp对象。
1
2
3
4
5
|
var
text =
'cat, bat, sat, fat'
;
// 使用/at/g 在全局中匹配at,并用ond进行替换
var
result = text.replace(/at/g,
'ond'
);
// cond, bond, sond, fond
console.log(result);
|
3. 考虑RegExp对象中捕获组的情况
RegExp具有9个用于存储捕获组的属性。$1, $2...$9,分别用于存储第一到九个匹配的捕获组。我们可以访问这些属性,来获取存储的值。
1
2
3
4
5
|
var
text =
'cat, bat, sat, fat'
;
// 使用/(.at)/g 括号为捕获组,此时只有一个,因此所匹配的值存放在$1中
var
result = text.replace(/(.at)/g,
'$($1)'
);
// $(cat), $(bat), $(sat), $(fat)
console.log(result);
|
4. 第二个参数为函数的情况,RegExp对象中不存在捕获组的情况
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
var
text =
'cat, bat, sat, fat'
;
// 使用/at/g 匹配字符串中所有的at,并将其替换为ond,
// 函数的参数分别为:当前匹配的字符,当前匹配字符的位置,原始字符串
var
result = text.replace(/at/g,
function
(match, pos, originalText) {
console.log(match +
' '
+ pos);
return
'ond'
});
console.log(result);
// 输出
/*
at 1 dd.html:12:9
at 6 dd.html:12:9
at 11 dd.html:12:9
at 16 dd.html:12:9
cond, bond, sond, fond dd.html:16:5
*/
|
5. 第二个参数为函数的情况,RegExp对象中存在捕获组的情况
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
var
text =
'cat, bat, sat, fat'
;
// 使用/(.at)/g 匹配字符串中所有的at,并将其替换为ond,
// 当正则表达式中存在捕获组时,函数的参数一次为:模式匹配项,第一个捕获组的匹配项,
// 第二个捕获组的匹配项...匹配项在字符串中的位置,原始字符串
var
result = text.replace(/.(at)/g,
function
() {
console.log(arguments[0] +
' '
+ arguments[1] +
' '
+ arguments[2]);
return
'ond'
});
console.log(result);
// 输出
/*
cat at 1
bat at 6
sat at 11
fat at 16
cond, bond, sond, fond
*/
|
以上为replace方法的所有可以使用的情况,下面我们使用replace和正则表达式共同实现字符串trim方法。
1
2
3
4
5
6
7
8
9
10
11
|
(
function
(myFrame) {
myFrame.trim =
function
(str) {
// ' hello world '
return
str.replace(/(^\s*)|(\s*$)/g,
''
);
};
window.myFrame = myFrame;
})(window.myFrame || {});
// 测试
var
str =
' hello world '
console.log(str.length);
// 15
console.log(myFrame.trim(str).length);
// 11
|
var n ="32121352132.15" ,
n = n.replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,')
document.write(n);
输出
32,121,352,132.15
这个/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g中的(?=pattern)正向肯定预查可以查询多次啊,比如第一次查询出123(...),把'123'换成'123,',然后继续查询出456(...),把'456'替换成'456,',再继续查就没有符合的了,所以查询替换停止了,最终替换变成了“123,456,789.00”。
var text = '3213216512.312';
// 使用/(.at)/g 匹配字符串中所有的at,并将其替换为ond,
// 当正则表达式中存在捕获组时,函数的参数一次为:模式匹配项,第一个捕获组的匹配项,
// 第二个捕获组的匹配项...匹配项在字符串中的位置,原始字符串
var result = text.replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g,function() {
console.log(arguments[0] + '@ ' + arguments[1] + '@ ' + arguments[2]+ '@ ' + arguments[3]);
return '$&,'
});
console.log(result);
输出效果:
3@ 512@ .312@ 0
213@ 512@ .312@ 1
216@ 512@ .312@ 4
$&,$&,$&,512.312
213@ 512@ .312@ 1
216@ 512@ .312@ 4
$&,$&,$&,512.312