javascriptでhtmlをアンエスケープする
- 2020.09.25
- javascript
- javascript

javascriptで、正規表現を使用して、htmlをアンエスケープするサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ firefox 80.0.1
htmlアンエスケープ処理
正規表現を利用した、以下のコードで、htmlをアンエスケープすることが可能です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// パターンを作成 const map = { "&": "&", """:'"', "<": "<", ">": ">", ''': "'", '`': '`', } var html = "<p>test</p>" var unescapedHtml = html.replace(/&(lt|gt|amp|quot|#x27|#x60);/g, match => map[match]); console.log(unescapedHtml); // 結果 <p>test</p> |
サンプルコード
以下は、
「エスケープ」ボタンをクリックすると、フォームに入力されたhtmlをアンエスケープして結果を表示する
サンプルコードとなります。
※cssには「bootstrap material」を使用してます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>mebeeサンプル</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons"> <link rel="stylesheet" href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css"> </head> <style> .main { margin: 0 auto; margin-top: 200px; display: flex; flex-direction: column; align-items: center; font-size: 30px; } </style> <script> // パターンを作成 const map = { "&": "&", """: '"', "<": "<", ">": ">", ''': "'", '`': '`', } function hoge() { // エスケープされたhtmlを取得 var html = document.getElementById("txtfrm").value; // 正規表現を利用してアンエスケープ var unescapedHtml = html.replace(/&(lt|gt|amp|quot|#x27|#x60);/g, match => map[match]); // 表示用の要素 var elm = document.getElementById("foo"); // アンエスケープ後の結果を表示 elm.textContent = unescapedHtml; } </script> <body> <div class="main"> <h2 id="foo" class="badge badge-primary">HTMLアンエスケープ</h2> <div class="form-group"> <label for="formGroupExampleInput" class="bmd-label-floating">エスケープされたhtml</label> <input id="txtfrm" type="text" class="form-control"> </div> <button onclick="hoge();" type="button" class="btn btn-raised btn-danger"> エスケープ </button> </div> </body> </html> |
アンエスケープされていることが確認できます。

-
前の記事
javascript オブジェクトを比較する 2020.09.25
-
次の記事
Nuxt.js ライブラリ「vue-masonry-wall」を使用して要素を無限に表示する 2020.09.26
コメントを書く