LoginSignup
5
8

More than 5 years have passed since last update.

JavaScriptのエスケープと改行変換

Last updated at Posted at 2016-11-11

備忘録
JavaScriptで表示する際に良く使う物。(足りてるかどうかは不明)
正規表現は毎回正解が分からないので、標準で安全な関数を用意して頂ければ良いのだが。

エスケープ

var escape = function(str){
    return 
        str.replace(/&/g, '&')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
}

改行処理

var nl2br = function(str) {
    return str.replace(/\r\n/g, "<br />").replace(/(\n|\r)/g, "<br />");
}
5
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
8