前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >第179天:javascript中replace使用总结

第179天:javascript中replace使用总结

作者头像
半指温柔乐
发布2018-09-11 09:44:43
4500
发布2018-09-11 09:44:43
举报

ECMAScript提供了replace()方法。这个方法接收两个参数,第一个参数可以是一个RegExp对象或者一个字符串,第二个参数可以是一个字符串或者一个函数。现在我们来详细讲解可能出现的几种情况。

1. 两个参数都为字符串的情况

1    var text = 'cat, bat, sat, fat';
2    // 在字符串中找到at,并将at替换为ond,只替换一次
3     var result = text.replace('at', 'ond');
4     // "cond, bat, sat, fat"
5     console.log(result);

2. 第一个参数为RegExp对象,第二个参数为字符串

  我们可以发现上面这种情况只替换了第一个at,如果想要替换全部at,就必须使用RegExp对象。

1 var text = 'cat, bat, sat, fat';
2     // 使用/at/g 在全局中匹配at,并用ond进行替换
3     var result = text.replace(/at/g, 'ond');
4     // cond, bond, sond, fond
5     console.log(result);

 3. 考虑RegExp对象中捕获组的情况。  

  RegExp具有9个用于存储捕获组的属性。$1, $2...$9,分别用于存储第一到九个匹配的捕获组。我们可以访问这些属性,来获取存储的值。

1  var text = 'cat, bat, sat, fat';
2 // 使用/(.at)/g 括号为捕获组,此时只有一个,因此所匹配的值存放在$1中
3  var result = text.replace(/(.at)/g, '$($1)');
4  // $(cat), $(bat), $(sat), $(fat)
5 console.log(result);

4. 第二个参数为函数的情况,RegExp对象中不存在捕获组的情况。

 1 var text = 'cat, bat, sat, fat';
 2      // 使用/at/g 匹配字符串中所有的at,并将其替换为ond,
 3      // 函数的参数分别为:当前匹配的字符,当前匹配字符的位置,原始字符串
 4      var result = text.replace(/at/g, function(match, pos, originalText) {
 5       console.log(match + '  ' + pos);
 6       return 'ond'
 7  });
 8 console.log(result);
 9  // 输出
10    /*
11    at  1  dd.html:12:9
12    at  6  dd.html:12:9
13    at  11  dd.html:12:9
14    at  16  dd.html:12:9
15  cond, bond, sond, fond  dd.html:16:5
16     */

5. 第二个参数为函数的情况,RegExp对象中存在捕获组的情况。

 1 var text = 'cat, bat, sat, fat';
 2     // 使用/(.at)/g 匹配字符串中所有的at,并将其替换为ond,
 3     // 当正则表达式中存在捕获组时,函数的参数一次为:模式匹配项,第一个捕获组的匹配项,
 4     // 第二个捕获组的匹配项...匹配项在字符串中的位置,原始字符串
 5     var result = text.replace(/.(at)/g, function() {
 6         console.log(arguments[0] + '  ' + arguments[1] + '  ' + arguments[2]);
 7         return 'ond'
 8     });
 9     console.log(result);
10     // 输出
11     /*
12         cat  at  1  
13         bat  at  6 
14         sat  at  11  
15         fat  at  16  
16         cond, bond, sond, fond 
17     */

以上为replace方法的所有可以使用的情况,下面我们使用replace和正则表达式共同实现字符串trim方法。

 1 (function(myFrame) {
 2         myFrame.trim = function(str) {
 3             // '  hello world  '
 4             return str.replace(/(^\s*)|(\s*$)/g, '');
 5         };
 6         window.myFrame = myFrame;
 7     })(window.myFrame || {});
 8     // 测试
 9     var str = '  hello world  '
10     console.log(str.length); // 15
11     console.log(myFrame.trim(str).length); // 11
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-02-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 两个参数都为字符串的情况
  • 2. 第一个参数为RegExp对象,第二个参数为字符串
  •  3. 考虑RegExp对象中捕获组的情况。  
  • 4. 第二个参数为函数的情况,RegExp对象中不存在捕获组的情况。
  • 5. 第二个参数为函数的情况,RegExp对象中存在捕获组的情况。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档