パターンに変数を用いる場合、RegExpオブジェクトを使わなければならないのだそうだ。
text
赤(レッド)
青(ブルー)
緑(グリーン)
col = new Array(); col["レッド"] = "red"; col["ブルー"] = "blue"; col["グリーン"] = "green"; for(key in col) { // text = text.replace(new RegExp("(" + key + ")"), "(" + col[key] + ")"); // errror // text = text.replace(new RegExp("\(" + key + "\)"), "(" + col[key] + ")"); // errror // text = text.replace(new RegExp('\(' + key + '\)'), "(" + col[key] + ")"); // errror // text = text.replace(new RegExp("/\(/" + key + "/\)/"), "(" + col[key] + ")"); // errror text = text.replace(new RegExp("." + key + "."), "(" + col[key] + ")"); // ok text = text.replace(new RegExp(/\(/ + key + /\)/), "(" + col[key] + ")"); // excellent! }
その第一引数に変数を含めた正規表現を書くことができるはずなんだけど、
()をエスケープできない。正規表現の処理自体はできている。エスケープだけが出来ない。
考えに考えて、この愚痴を書き進めてようやくたどり着いたのが一番下。これで通った。
ちなみに、資料をかなり漁ったけどこの記法を紹介しているページは一つもなかった。
おそらくエスケープしないのであれば""で通るためだと思われる。
これはjsの仕様が変なのか、解説ページが片手落ちなのか。