深入瞭解下replace函式

hellomarker發表於2019-03-12

起因

由於之前自己對replace不熟悉的緣故,寫的程式碼又臭又長,所以特地來深入的瞭解下replace。

想看具體程式碼可移步 記一次字串切割的工作

replace語法

str.replace(regexp|substr, newSubStr|function)
複製程式碼

可以看到replace使用正規表示式或字串來匹配字串,使用字串或函式返回值做替換字串

如果按不同形式的傳參來細分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第二個引數的兩種形態。

深入瞭解下replace函式

深入瞭解下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文件中可以找到

相關文章