JavaScript

JavaScriptで正規表現置換やマッチを行う方法

基本

  • 置換
    var str=”foobar-foobar”
    undefined
    str.replace(‘foo’,’bar’)
    “barbar-foobar”
  • 文字列を含むかを真偽値で返す
    var str = “Hello world, welcome to the universe.”;
    str.includes(“world”);
    true

正規表現(regex)

  • replace()
    var re = /(\w+)\s(\w+)/igm;
    var str = ‘John Smith’;
    var newstr = str.replace(re, ‘$2, $1’);
    console.log(newstr); // Smith, John
    Smith, John
  • match()
    var re = /(\w+)\s(\w+)/igm;
    var str = ‘John Smith foobar John Smith’;
    var newstr = str.match(re);
    console.log(newstr); // Smith, John
    VM29918:4 (2) [“John Smith”, “foobar John”]
  • test(): True or false
    var re = /(\w+)\s(\w+)/igm;
    var str = ‘John Smith foobar John Smith’;
    var newstr = re.test(str)
    console.log(newstr);
    VM30242:4 true
    undefined
    var re = /(\w+)\s\n\n\n\n(\w+)/igm;
    var str = ‘John Smith foobar John Smith’;
    var newstr = re.test(str)
    console.log(newstr);
    VM30250:4 false

test()はreplace()などとは相対的に,正規表現パターンをオブジェクトとするので注意
正規表現パターンは別に定義するのが肝.

  • 装飾子
    • i: 大文字と小文字を区別しない一致を実行する
    • g: グローバルマッチを実行する(最初のマッチの後に停止するのではなく、すべてのマッチを見つける)
    • m: 複数行のマッチングを実行する

References:
replace:
https://www.w3schools.com/jsref/jsref_obj_regexp.asp
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace
match:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/match
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です