How do I add slashes to a string in Javascript?

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

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

8条回答
  •  粉色の甜心
    2020-12-29 19:31

    Following JavaScript function handles ', ", \b, \t, \n, \f or \r equivalent of php function addslashes().

    function addslashes(string) {
        return string.replace(/\\/g, '\\\\').
            replace(/\u0008/g, '\\b').
            replace(/\t/g, '\\t').
            replace(/\n/g, '\\n').
            replace(/\f/g, '\\f').
            replace(/\r/g, '\\r').
            replace(/'/g, '\\\'').
            replace(/"/g, '\\"');
    }
    

提交回复
热议问题