Help us understand the problem. What is going on with this article?

特定の文字列を全て置換する[Javascript]

More than 1 year has passed since last update.

"apple,banana,orange" のような文字列を "apple banana orange" に置き換えたいとします。
(カンマを半角スペースに)
PHPですと以下のように、

php
<?php
$str = "apple,banana,orange";
str_replace(',', ' ', $str);

と、str_replace() を呼ぶことで全て置換することができます。
PHP:str_replace

しかし同様のノリでjavasciptで書くと...

javascript
const str = "apple,banana,orange";
const replaced = str.replace(',', ' ')
console.log(replaced) // apple banana,orange

と、マッチした先頭のものしか置換されません。

正規表現

String.prototype.replace()で全置換をする場合、正規表現を使います。

javascript
const str = "apple,banana,orange";
const replaced = str.replace(/,/g, ' ')
console.log(replaced) // apple banana orange

上記のように第一引数に正規表現リテラル(もしくはRegExpオブジェクト)を渡します。
またgフラグをつけることで、全てのマッチを探すことができます。
String.prototype.replace()
RegExp

split + join を組み合わせる

javascript
let str = "apple,banana,orange"
str = str.split(',') // ["apple", "banana", "orange"]
str.join(' ') // "apple banana orange"

String.prototype.split() は、引数に渡された文字で文字列を分割して、配列形式にして返します。
そして Array.prototype.join()は、引数に渡された文字で配列の要素を連結して、文字列にします。
String.prototype.split()
Array.prototype.join()

DecoratedKnight
今はフロントエンドやってる
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした