深刻了解下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

相關文章
相關標籤/搜索