Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
25
Help us understand the problem. What is going on with this article?
@naoyashiga

replaceに変数を使ってグローバルマッチさせる2つの方法

More than 5 years have passed since last update.

やりたいこと

index.htmlの全ての「も」を「M」に置換したいとします。

index.html
<p id='test'>すもももももももものうち</p>

問題

置換したい文字列を変数beforeに代入します。変数beforeをreplaceにそのまま入れると、最初の該当箇所しか置換されません。

test1.js
var before = "";
var after = "M";
var txt = $("#test").html();

var replaceText = txt.replace(before,after);
$("#test").html(replaceText);
//出力結果:すMももももももものうち

解決策1

該当箇所全てを置換するにはRegExp オブジェクトにグローバルマッチのフラグ (g)をつけます。

test2.js
var replaceText = txt.replace(new RegExp(before,"g"),after);
//出力結果:すMMMMMMMMのうち

解決策2

変数beforeに最初からフラグをつけておきます。

test3.js
var before = /も/g;
var after = "M";
var txt = $("#test").html();

var replaceText = txt.replace(before,after);
$("#test").html(replaceText);
//出力結果:すMMMMMMMMのうち

・参考ページ
String.replace - JavaScript | MDN(https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String/replace)

25
Help us understand the problem. What is going on with this article?
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
naoyashiga
クリエイティブ開発者

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
25
Help us understand the problem. What is going on with this article?