jQuery replaceメソッドに正規表現を使って複数の文字列を置き換えるサンプル

環境
Google Chrome 107.0.5304.88
Windows 10 home 64bit
jQuery 3.6.0

構文
文字列.replace(/置換前文字/g,"置換後文字")
正規表現のオプションのgを使用して、複数の同じ文字を置き換えます。
replace(regexp, newSubstr)
引数

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
regexp (pattern)
RegExp オブジェクト、またはリテラルです。一致すると、第 2 引数の newSubstr または replacerFunction の返値と置き換えられます。
newSubstr (replacement)
regexp や substr 引数で指定される部分文字列を置換する文字列です。数々の特別な置換パターンに対応しています。
regexp (pattern) RegExp オブジェクト、またはリテラルです。一致すると、第 2 引数の newSubstr または replacerFunction の返値と置き換えられます。 newSubstr (replacement) regexp や substr 引数で指定される部分文字列を置換する文字列です。数々の特別な置換パターンに対応しています。
regexp (pattern)
RegExp オブジェクト、またはリテラルです。一致すると、第 2 引数の newSubstr または replacerFunction の返値と置き換えられます。

newSubstr (replacement)
regexp や substr 引数で指定される部分文字列を置換する文字列です。数々の特別な置換パターンに対応しています。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
// ボタン「置換」のクリックイベント
$("#btnchg").click(function() {
let str = $("#show").text();
// 複数の同じ文字を置き換る
$("#show").text(str.replace(/s/g,"TT"));
});
});
</script>
</head>
<body>
<p>目標:<span id="show">study skill</span></p>
<input type="button" id="btnchg" value="置換" />
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(function(){ // ボタン「置換」のクリックイベント $("#btnchg").click(function() { let str = $("#show").text(); // 複数の同じ文字を置き換る $("#show").text(str.replace(/s/g,"TT")); }); }); </script> </head> <body> <p>目標:<span id="show">study skill</span></p> <input type="button" id="btnchg" value="置換" /> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){ 
  // ボタン「置換」のクリックイベント
  $("#btnchg").click(function() {
      let str = $("#show").text();
      // 複数の同じ文字を置き換る
      $("#show").text(str.replace(/s/g,"TT"));
  });
});
</script>
</head>
<body>

<p>目標:<span id="show">study skill</span></p>
<input type="button" id="btnchg" value="置換" />

</body>
</html>

実行結果
「置換」ボタンを押すと、文字「study skill」を「TTtudy TTkill」になります。

jQuery

Posted by arkgame