深刻了解下replace函数

原由

因为以前本身对replace不熟悉的缘故,写的代码又臭又长,因此特意来深刻的了解下replace。javascript

想看具体代码可移步 记一次字符串切割的工做java

replace语法

str.replace(regexp|substr, newSubStr|function) 复制代码

能够看到replace使用正则表达式或字符串来匹配字符串,使用字符串或函数返回值作替换字符串react

若是按不一样形式的传参来细分replace的话,我以为不够好,因此我决定按功能特色进行区分对比。正则表达式

匹配一个 && 匹配多个

var p = "The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?";

  // 匹配一个
  console.log(p.replace("the", `123`)); 
  console.log(p.replace(/the/, `123`)); 
  //The quick brown fox jumps over 123 lazy dog. If the dog reacted, was it really lazy?
  
  // 匹配多个
  console.log(p.replace(/the/g, `123`)); 
  //The quick brown fox jumps over 123 lazy dog. If 123 dog reacted, was it really lazy?
复制代码

直接替换 && 根据匹配字符串灵活替换

对比以前先了解MDN文档中对于replace第二个参数的两种形态。函数

var p = "The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?";

  // 直接替换
  console.log(p.replace(/the/, `123`)); 
  //The quick brown fox jumps over 123 lazy dog. If the dog reacted, was it really lazy?
  

  // 根据匹配字符串灵活替换
  // $& == 替换函数的第一个参数match == 匹配字符串
  console.log(p.replace("the", "$&"));
  console.log(p.replace("the", match => match));
  //The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?
  
  console.log(p.replace(/the/g, "$&123"));
  console.log(p.replace(/the/g, match => match+'123'));
  //The quick brown fox jumps over the123 lazy dog. If the123 dog reacted, was it really lazy?
  
  // $n == 替换函数的第n+1个参数 == 匹配正则表达式中第n个括号
  console.log(p.replace(/(t)(h)(e)/g, "$2")); 
  console.log(p.replace(/(t)(h)(e)/g, (match,p1,p2,p3) => p2));
  //The quick brown fox jumps over h lazy dog. If h dog reacted, was it really lazy?
  // 可实际运用于将匹配字符串的第一位转大写的需求
  console.log(p.replace(/(t)(h)(e)/g, (match,p1,p2,p3) => p1.toUpperCase()+p2+p3));
  //The quick brown fox jumps over The lazy dog. If The dog reacted, was it really lazy?
  
  // $` == 当前匹配的子串左边的内容。 == string.substring(0,offset)
  console.log(p.replace("the", "$`"));
  console.log(p.replace("the", (match, offset,string) => string.substring(0,offset)));
  //The quick brown fox jumps over The quick brown fox jumps over lazy dog. If the dog reacted, was it really lazy?
  // $' == 当前匹配的子串右边的内容。 == string.substring(offset+match.length,string.length)
  console.log(p.replace("the", "$'"));
  console.log(p.replace("the", (match, offset,string) => string.substring(offset+match.length,string.length)));
  //The quick brown fox jumps over lazy dog. If the dog reacted, was it really lazy? lazy dog. If the dog reacted, was it really lazy?
复制代码

以上全部引用都为MDN文档中能够找到post

相关文章
相关标签/搜索