javascript中replace使用方法总结

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

创新互联是一家专注于成都网站设计、做网站、成都外贸网站建设公司与策划设计,二七网站建设哪家好?创新互联做网站,专注于网站建设10余年,网设计领域的专业建站公司;建站业务涵盖:二七等地区。二七做网站价格咨询:18980820575

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

 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对象。

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,分别用于存储第一到九个匹配的捕获组。我们可以访问这些属性,来获取存储的值。

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对象中不存在捕获组的情况

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对象中存在捕获组的情况

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方法。

(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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。

文章标题:javascript中replace使用方法总结
网页网址:https://www.cdcxhl.com/article24/ijpgce.html

成都网站建设公司_创新互联,为您提供定制开发企业建站网站维护手机网站建设全网营销推广网站设计

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

h5响应式网站建设