How do I add slashes to a string in Javascript?

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

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

相关标签:
8条回答
  • 2020-12-29 19:46

    replace works for the first quote, so you need a tiny regular expression:

    str = str.replace(/'/g, "\\'");
    
    0 讨论(0)
  • 2020-12-29 19:49
    var str = "This is a single quote: ' and so is this: '";
    console.log(str);
    
    var replaced = str.replace(/'/g, "\\'");
    console.log(replaced);
    

    Gives you:

    This is a single quote: ' and so is this: '
    This is a single quote: \' and so is this: \'
    
    0 讨论(0)
提交回复
热议问题