How do I add slashes to a string in Javascript?

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

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

8条回答
  •  醉梦人生
    2020-12-29 19:31

    if (!String.prototype.hasOwnProperty('addSlashes')) {
        String.prototype.addSlashes = function() {
            return this.replace(/&/g, '&') /* This MUST be the 1st replacement. */
                 .replace(/'/g, ''') /* The 4 other predefined entities, required. */
                 .replace(/"/g, '"')
                 .replace(/\\/g, '\\\\')
                 .replace(//g, '>').replace(/\u0000/g, '\\0');
            }
    }
    

    Usage: alert(str.addSlashes());

    ref: https://stackoverflow.com/a/9756789/3584667

提交回复
热议问题