How do I replace a double-quote with an escape-char double-quote in a string using JavaScript?

前端 未结 4 1183
臣服心动
臣服心动 2020-12-29 01:57

Say I have a string variable (var str) as follows-

Dude, he totally said that "You Rock!"

Now If I\'

4条回答
  •  醉梦人生
    2020-12-29 02:14

    The other answers will work for most strings, but you can end up unescaping an already escaped double quote, which is probably not what you want.

    To work correctly, you are going to need to escape all backslashes and then escape all double quotes, like this:

    var test_str = '"first \\" middle \\" last "';
    var result = test_str.replace(/\\/g, '\\\\').replace(/\"/g, '\\"');
    

    depending on how you need to use the string, and the other escaped charaters involved, this may still have some issues, but I think it will probably work in most cases.

提交回复
热议问题