JavaScript backslash (\) in variables is causing an error

前端 未结 6 2064
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 15:19

In Javascript, when I put a backslash in some variables like:

var ttt = \"aa ///\\\\\\\";
var ttt = \"aa ///\\\"; 

Javascript shows an erro

6条回答
  •  清歌不尽
    2020-11-22 16:01

    You may want to try the following, which is more or less the standard way to escape user input:

    function stringEscape(s) {
        return s ? s.replace(/\\/g,'\\\\').replace(/\n/g,'\\n').replace(/\t/g,'\\t').replace(/\v/g,'\\v').replace(/'/g,"\\'").replace(/"/g,'\\"').replace(/[\x00-\x1F\x80-\x9F]/g,hex) : s;
        function hex(c) { var v = '0'+c.charCodeAt(0).toString(16); return '\\x'+v.substr(v.length-2); }
    }
    

    This replaces all backslashes with an escaped backslash, and then proceeds to escape other non-printable characters to their escaped form. It also escapes single and double quotes, so you can use the output as a string constructor even in eval (which is a bad idea by itself, considering that you are using user input). But in any case, it should do the job you want.

提交回复
热议问题