0
0

More than 1 year has passed since last update.

[JavaScript] 正規表現とsplitを使って特定の文字列を置換する

Posted at

ある文字列から、特定の文字列を除いて新たな文字列を作成するために
正規表現を使ったので、覚えておくために記事にしました。
同じようなことを実装するときに、この記事が少しでもお役に立てれば幸いです。

文字列を分割する

ある特定の文字の後ろで文字列を分割します。

  const str ='ラジオ体操第一'
  const regex = /(?<=体操)/;
  const words = str.split(regex); //   [ 'ラジオ体操', '第一' ]

あとは配列の要素を置換するか、削除することで、目的の文字列を得ることができます。

配列の操作は、置換や削除、追加といろいろ使えるspliceを使いました。

最後に配列の要素をつなげて文字列にするjoinを使います。

  words.splice(1,1) 
  console.log(words.join()) // 'ラジオ体操'

文字列の置換を行う場合、replaceを使う方法もありますが、

大量の文字列を扱い、特定の文字以降が同じ文字列ではない場合などは、使えるのではないかと思います。

参考にしたサイト

0
0
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
0
0