How do I add slashes to a string in Javascript?

后端 未结 8 1765
陌清茗
陌清茗 2020-12-29 19:05

Just a string. Add \\\' to it every time there is a single quote.

8条回答
  •  甜味超标
    2020-12-29 19:38

    A string can be escaped comprehensively and compactly using JSON.stringify. It is part of JavaScript as of ECMAScript 5 and supported by major newer browser versions.

    str = JSON.stringify(String(str));
    str = str.substring(1, str.length-1);
    

    Using this approach, also special chars as the null byte, unicode characters and line breaks \r and \n are escaped properly in a relatively compact statement.

提交回复
热议问题