5

文字列の一致をその場で置き換える最良の方法を考えているだけです。

value.replace("bob", "fred");

たとえば、動作しますが、「bob」の各インスタンスを、配列に格納したランダムな文字列に置き換えたいと考えています。正規表現の一致を行うだけで一致するテキストが返されますが、元の文字列でそれを置き換えることはできません。これを行う簡単な方法はありますか?

たとえば、次の文字列が必要です。

"Bob went to the market. Bob went to the fair. Bob went home"

多分飛び出すために

"Fred went to the market. John went to the fair. Alex went home"
4

1 に答える 1

4

関数呼び出しの値に置き換えることができます。

var names = ["Fred", "John", "Alex"];
var s = "Bob went to the market. Bob went to the fair. Bob went home";
s = s.replace(/Bob/g, function(m) {
    return names[Math.floor(Math.random() * names.length)];
});

たとえば、次のようになります。

"John went to the market. Fred went to the fair. John went home"
于 2012-06-14T00:37:07.413 に答える