Javascript 如何在javascript中用\替换“

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7044365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:35:14  来源:igfitidea点击:

How to replace " with \" in javascript

javascriptreplace

提问by Darcy

I have a textbox that posts info to the server and it's in JSON format. Lets say I want to enter two quotes for the value, and the JSON struct would look like:

我有一个将信息发布到服务器的文本框,它采用 JSON 格式。假设我想为该值输入两个引号,JSON 结构如下所示:

{
    "test": """"
}

I need it to look like:

我需要它看起来像:

{
    "test": "\"\""
}

so it will follow JSON standards and can be parsable/stringifyable.

所以它将遵循 JSON 标准并且可以解析/字符串化。

I tried using

我尝试使用

 var val = myVal.replace('"', "\\"");

but this didn't work. valends up with only one escaped quote like so \""Any help is much appreciated!

但这没有用。val最终只有一个这样的转义引语,\""非常感谢任何帮助!

回答by Lightness Races in Orbit

My answer makes some assumptions, as I've had to fill in the rather sizeable gaps in your question:

我的回答做了一些假设,因为我不得不填补你问题中相当大的空白:

  • The user will enter a text string into a textbox;
  • Your script will read the textbox contents, and use those contents as the valueof one of the items in a JSON string that it's building;
  • The script sends this resulting JSON string to the server somehow.
  • 用户将在文本框中输入一个文本字符串;
  • 您的脚本将读取文本框内容,并将这些内容用作它正在构建的 JSON 字符串中的项目之一的
  • 该脚本以某种方式将此生成的 JSON 字符串发送到服务器。

If I've got that right, let's proceed...

如果我猜对了,让我们继续......



Baseline code

基线代码

So, with some placeholders, you're doing:

因此,使用一些占位符,您正在执行以下操作:

function get_contents_of_textbox() {
   // Dummy data for example
   return 'My mum pushed and I said "Hello World"!';
}

function send_to_server(json_str) {
   // Dummy action: display JSON string
   console.log(json_str);
}

var myVal = get_contents_of_textbox();
var JSON  = '{ "test": "' + myVal + '" }';
send_to_server(JSON);

Live demo, showing the malformed JSON.

现场演示,显示格式错误的 JSON。



Initial attempt

初步尝试

To ensure that JSONis valid, escapeany quotes and backslashes that it may contain. You already gave it a go:

为确保它JSON有效,请转义它可能包含的任何引号和反斜杠。你已经试过了:

myVal = myVal.replace('"', "\\"");

and the result of your attemptis:

您尝试的结果是:

{ "test": "My mum pushed and I said \"Hello World"!" }

Only the first quote has been escaped. This is because only one instance of the search string is replaced by default.

只有第一个引用被转义了。这是因为默认情况下仅替换搜索字符串的一个实例。

The Mozilla documentation says:

Mozilla 文档

To perform a global search and replace, either include the g flag in the regular expression or if the first parameter is a string, include g in the flags parameter.

要执行全局搜索和替换,请在正则表达式中包含 g 标志,或者如果第一个参数是字符串,则在 flags 参数中包含 g。



Working attempt

工作尝试

Unfortunately, the flagsparameter is non-standard, so let's switch to the regex version of replace, and use the /gswitch in it:

不幸的是,该flags参数是非标准的,所以让我们切换到 的正则表达式版本replace,并使用其中的/g开关:

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

(You'll notice that I also condensed the replacement string, for brevity.)

(您会注意到,为了简洁起见,我还压缩了替换字符串。)

Result:

结果:

{ "test": "My mum pushed and I said \"Hello World\"!" }

Live demo.Hurrah!

现场演示。欢呼!



Complete solution

完整的解决方案

Let's also add logic to escape backslashes, and we end up with this:

让我们也添加逻辑来转义反斜杠,我们最终得到这样的结果:

function get_contents_of_textbox() {
   // Dummy data for example
   return 'My mum pushed [a back\slash] and I said "Hello World"!';
}

function send_to_server(json_str) {
   // Dummy action: display JSON string
   console.log(json_str);
}

var myVal = get_contents_of_textbox();
myVal = myVal.replace(/\/g, '\\'); // escape backslashes
myVal = myVal.replace(/"/g, '\"');   // escape quotes

var JSON  = '{ "test": "' + myVal + '" }';
send_to_server(JSON);

Result:

结果:

{ "test": "My mum pushed [a back\slash] and I said \"Hello World\"!" }

Live demo.

现场演示。

回答by Mrchief

Use this

用这个

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

回答by Marc B

Just create a JS array

只需创建一个 JS 数组

var arr = {
   test: '""'
}

and let the JSON interface handle the escaping for you. You shouldn't ever have to deal with the details yourself.

并让 JSON 接口为您处理转义。您不应该自己处理细节。

回答by Endophage

As you said you're getting the string from a textbox you don't need to do anything to it to get it back to the server. If you get the value of the textbox via jQuery's $()notation or pure document.getElementByIdit will already be properly escaped. JavaScript doesn't take the value of your textbox and try to put it in quotes.

正如您所说,您从文本框中获取字符串,您无需对其进行任何操作即可将其返回到服务器。如果您通过 jQuery 的$()表示法或纯获取文本框的值,document.getElementById它将已经被正确转义。JavaScript 不会获取文本框的值并尝试将其放在引号中。

If you text box has ""entered into it, document.getElementById('mytextbox').valueis not equal to "\"\"". The backslashes are only necessary when you are defining a string literal.

如果您的文本框已""输入其中,document.getElementById('mytextbox').value则不等于"\"\""。只有在定义字符串文字时才需要反斜杠。

Try removing all your escaping and regex replacing and just send back the data from the text box without doing anything to it. Your json should look something like:

尝试删除所有转义和正则表达式替换,只需从文本框中发回数据而不对其进行任何操作。您的 json 应该类似于:

{
    "test" : document.getElementById('myTextBox')
}