LoginSignup
6
3

More than 5 years have passed since last update.

正規表現で単語の区切り

Posted at

\b は単語の区切りにマッチします。

console.log("Let it be.".match(/\bit\b/));
// [ 'it', index: 4, input: 'Let it be.' ]
console.log("Git is awesome.".match(/\bit\b/));
// null

「単語が区切られていること」にマッチするのであって、「単語を区切る文字」そのものにマッチするわけではありません。

逆に「単語の区切りでない」という指定には \B を使います。

console.log("Let it be.".match(/\Bit/));
// null
console.log("Git is awesome.".match(/\Bit/));
// [ 'it', index: 1, input: 'Git is awesome.' ]

なお [\b] はバックトレースにマッチするそうなので、注意です。

参考
RegExp - JavaScript | MDN

6
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3