配列に含まれる値すべてを別のTextでreplaceしたいです。
配列だと想定通りに動作しないのですが、どのようにすればいいのでしょうか。
JavaScript
1// 通常の文字列 2let newText = ''; 3const text = '㌘'; 4let regExp = new RegExp('㌘', "g"); 5newText = text.replace(regExp, 'aaaa'); 6console.log('1st:' + newText); 7 8// 配列から 9const textArr = ['㌘', 'a', 'b']; 10textArr.forEach((item) =>{ 11 console.log(item); 12 regExp = new RegExp(item, "g"); 13 newText = text.replace(regExp, 'aaaa'); 14}) 15console.log('2nd:' + newText);
結果は以下です。
1st:aaaa ㌘ a b 2nd:㌘
追記
すみません、情報が不足しておりました。
配列に含まれるものをすべて'aaaa'に置換したいという要件でした。
例でいうと期待する結果は
2nd:aaaa
です
どういう結果を期待したのか不明です。個々の置換結果を見たいのなら、console.log('2nd:' + newText);をループの中に入れないと。
回答3件
あなたの回答
tips
プレビュー