Escape quotes in JavaScript

前端 未结 13 796
不思量自难忘°
不思量自难忘° 2020-11-22 11:39

I\'m outputting values from a database (it isn\'t really open to public entry, but it is open to entry by a user at the company -- meaning, I\'m not worried about XSS).

13条回答
  •  轮回少年
    2020-11-22 12:12

    You can copy those two functions (listed below), and use them to escape/unescape all quotes and special characters. You don't have to use jQuery or any other library for this.

    function escape(s) {
        return ('' + s)
            .replace(/\\/g, '\\\\')
            .replace(/\t/g, '\\t')
            .replace(/\n/g, '\\n')
            .replace(/\u00A0/g, '\\u00A0')
            .replace(/&/g, '\\x26')
            .replace(/'/g, '\\x27')
            .replace(/"/g, '\\x22')
            .replace(//g, '\\x3E');
    }
    
    function unescape(s) {
        s = ('' + s)
           .replace(/\\x3E/g, '>')
           .replace(/\\x3C/g, '<')
           .replace(/\\x22/g, '"')
           .replace(/\\x27/g, "'")
           .replace(/\\x26/g, '&')
           .replace(/\\u00A0/g, '\u00A0')
           .replace(/\\n/g, '\n')
           .replace(/\\t/g, '\t');
    
        return s.replace(/\\\\/g, '\\');
    }
    

提交回复
热议问题