javascript replaceAllを使用して全て置換する
- 作成日 2022.02.22
- 更新日 2022.10.12
- javascript
- javascript
javascriptで、replaceAllを使用して全て置換するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 106.0.5249.103
replaceAll
「replaceAll」を使用すると初めの文字だけ置換する「replace」とは違い、全て置換することができます。
replaceAll('対象の文字列','置換する文字列')
実際に、両方実行してみます。
const result1 = 'mebee'.replace('e','a');
console.log(result1); // mabee
const result2 = 'mebee'.replaceAll('e','a');
console.log(result2); // mabaa
実行結果を見ると、「replaceAll」は全て置換されていることが確認できます。
以下のように、正規表現を使用しても全置換が実行できます。
const result = 'mebee'.replace(/e/g,'a');
console.log(result); // mabaa
「split」で分割してから「join」で結合する方法もあります。
const result = 'mebee'.split('e').join('a');
console.log(result); // mabaa
サンプルコード
以下は、
「実行」ボタンをクリックした際に、フォームの値から半角スペースを全て除去するサンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.tailwindcss.com"></script>
</head>
<script>
const hoge = () => {
const result = str.value.replaceAll(' ','');
str.value = result
}
window.onload = () => {
btn.onclick = () => { hoge() };
}
</script>
<body>
<div class="container mx-auto my-56 w-64 px-4">
<div id="sample" class="flex flex-col justify-center">
<h1 class="font-semibold text-rose-500 text-lg mr-auto">実行結果</h1>
<input
class="mb-2 shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
id="str" type="text">
<button id="btn"
class="mb-2 md:mb-0 bg-transparent hover:bg-violet-500 text-violet-700 font-semibold hover:text-white py-2 px-4 border border-violet-500 hover:border-transparent rounded">
実行
</button>
</div>
</div>
</body>
</html>
実行結果を確認すると、半角スペースが除去されていることが確認できます。
-
前の記事
MySQL 日付を四半期単位で取得する 2022.02.21
-
次の記事
python PySimpleGUIでtreeのfontとサイズを設定する 2022.02.22
コメントを書く