jsで置換え
- <!DOCTYPE html>
- <html lang="ja">
- <head>
- <meta charset="UTF-8">
- <title>jsで置換え</title>
- </head>
- <body>
- <h1>jsで置換え</h1>
- <script type="text/javascript">
- str = "ABCabcdefABCabcABC";
- document.write("オリジナル: str = " + str);
- document.write("<br /><br />");
- document.write("最初に見つかった「abc」を「ooo」にする:<br />");
- document.write("内容: " + 'str.replace("abc", "ooo")' + "<br />");
- document.write("結果: " + str.replace("abc", "ooo") + "<br />");
- document.write("<br />");
- document.write("すべての「abc」を「ooo」にする:<br />");
- document.write("内容: " + 'replaceAll(str, "abc", "ooo")' + " ※replaceAll()は別途宣言。<br />");
- document.write("結果: " + replaceAll(str, "abc", "ooo") + "<br />");
- document.write("<br />");
- document.write("正規表現を使って最初に見つかった「abc」を「ooo」にする:<br />");
- document.write("内容: " + 'str.replace(/abc/, "ooo")' + "<br />");
- document.write("結果: " + str.replace(/abc/, "ooo") + "<br />");
- document.write("<br />");
- document.write("正規表現を使って最初に見つかった「abc(大文字・小文字区別なし)」を「ooo」にする:<br />");
- document.write("内容: " + 'str.replace(/abc/i, "ooo")' + "<br />");
- document.write("結果: " + str.replace(/abc/i, "ooo") + "<br />");
- document.write("<br />");
- document.write("正規表現を使ってすべての「abc」を「ooo」にする:<br />");
- document.write("内容: " + 'strstr.replace(/abc/g, "ooo")' + "<br />");
- document.write("結果: " + str.replace(/abc/g, "ooo") + "<br />");
- document.write("<br />");
- document.write("正規表現を使ってすべての「abc(大文字・小文字区別なし)」を「ooo」にする:<br />");
- document.write("内容: " + 'str.replace(/abc/gi, "ooo")' + "<br />");
- document.write("結果: " + str.replace(/abc/gi, "ooo") + "<br />");
- document.write("<br />");
- document.write("<hr>");
- repStr = "abc";
- document.write("変数を使う:<br />");
- document.write("変数のオリジナル: repStr = " + repStr);
- document.write("<br /><br />");
-
- document.write("変数に「abc」をいれて対象すべてを「ooo」にする:<br />");
- document.write("内容: " + 'str.replace(new RegExp(repStr, "g"), "ooo")' + "<br />");
- document.write("結果: " + str.replace(new RegExp(repStr, "g"), "ooo") + "<br />");
- document.write("<br />");
- document.write("変数に「abc」をいれて対象すべて(大文字・小文字区別なし)を「ooo」にする:<br />");
- document.write("内容: " + 'str.replace(new RegExp(repStr, "gi"), "ooo")' + "<br />");
- document.write("結果: " + str.replace(new RegExp(repStr, "gi"), "ooo") + "<br />");
- document.write("<br />");
- // 対象の文字列を全部置換え
- function replaceAll(str, findStr, replaceStr)
- {
- return str.split(findStr).join(replaceStr);
- }
- </script>
- <div style="font-size:10pt;text-align:right;margin-top:0.5em;">
- <a href="//tips.recatnap.info/" target="_top">PCスキルの小技・忘却防止メモ</a> -
- <a href="//tips.recatnap.info/wiki/" target="_top">PCスキルの小技・忘却防止メモのまとめ(wiki)</a>
- </div>
- <div style="font-size:10pt;text-align:center;margin-top:0.5em;padding:0.5em;border-top:1px solid #ccc;">
- Copyright © 2009 by PCスキルの小技・忘却防止メモ. All rights reserved.
- </div>
- </body>
- </html>