「Google Apps Script」正規表現でマッチした文字列を全て置換するサンプル

構文
const 変数名 = /正規表現式/g
対象文字列.replace(変数名, “置換文字")
正規表現のオプションが「g」を指定して、マッチしたものをすべて返します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function myFunction() {
const strA = "<5678912340>";
const regA = /[0-9]{5}/g;
console.log(strA.replace(regA, "##"));
const strB = "<2345123450>";
const regB = /[0-9]{5}/;
console.log(strB.replace(regB, "★★"));
}
function myFunction() { const strA = "<5678912340>"; const regA = /[0-9]{5}/g; console.log(strA.replace(regA, "##")); const strB = "<2345123450>"; const regB = /[0-9]{5}/; console.log(strB.replace(regB, "★★")); }
function myFunction() {
 
  const strA = "<5678912340>"; 
  const regA = /[0-9]{5}/g;
  console.log(strA.replace(regA, "##"));

  const strB = "<2345123450>";
  const regB = /[0-9]{5}/;
  console.log(strB.replace(regB, "★★")); 

}

実行結果
<####>
<★★23450>

Google Apps Script

Posted by arkgame