简体   繁体   English

从变量中的字符串转义 JavaScript 中的双引号

[英]Escaping double quotes in JavaScript from a string in a variable

I have these two scenarios:我有这两种情况:


console.log(('hello "friend" what\'s up?').replace(/\"/g, '\\"'));

I receive the expected result:我收到了预期的结果:

hello "friend" what's up?你好“朋友”怎么了?


But , if I do this:但是,如果我这样做:

var val = 'hello "friend" what\'s up?';
val.replace(/\"/g, '\\"');
console.log(val);

I get...我得到...

hello "friend" what's up?你好“朋友”怎么了?

(the result needs to be hello \\"friend\\" what's up? ) (结果需要是hello \\"friend\\" what's up?


The only difference is that the second one uses an already created variable that contains the string.唯一的区别是第二个使用了一个已经创建的包含字符串的变量。 Why doesn't the second scenario actually replace the double quotes with \\" ?为什么第二种情况实际上没有用\\"替换双引号?

From the MDN documentation :MDN 文档

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. replace() 方法返回一个新字符串,其中部分或所有模式匹配项被替换项替换。

You need to do val = val.replace(/\\"/g, '\\\\"');你需要做val = val.replace(/\\"/g, '\\\\"'); so that you're assigning the new string returned by calling replace to your variable.这样您就可以将通过调用replace返回的新字符串分配给您的变量。

Actually by doing实际上通过做

val.replace(/\"/g, '\\"');

You're not assigning the replaced value back to val .您没有将替换的值分配回val For that you will need:为此,您将需要:

val = val.replace(/\"/g, '\\"');
val.replace(/\"/g, '\\"');

In the above code you are not reassigning to val ;在上面的代码中,您没有重新分配给val

Try this to get the expected result.试试这个以获得预期的结果。

val = val.replace(/\"/g, '\\"');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM