javascript 使用包含双引号的字符串填充输入字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5383520/
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-10-25 17:01:17  来源:igfitidea点击:

Populate an input field with a string that contains a double quote

javascriptescaping

提问by Phillip Senn

I'm getting a value back from the server that contains a double quote in it. I need to populate an input tag with the value.

我从服务器返回一个包含双引号的值。我需要用值填充输入标签。

I've tried using escape(myVariable), but that converts the spaces to %20, etc. I suppose I could write an if/then that says if there's a double quote in the field, then use value='', but then what do I do if they have both double and single quotes in the field?

我试过使用转义(myVariable),但将空格转换为 %20 等。我想我可以写一个 if/then 表示如果字段中有双引号,然后使用 value='',但是然后如果字段中有双引号和单引号,我该怎么办?

回答by Mark Kahn

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

回答by Peter Olson

Replace double quotes with ".

".替换双引号。

回答by James

I'm getting a value back from the server that contains a double quote in it.

我从服务器返回一个包含双引号的值。

You flagged your question as "javascript" so I assume you are loading this server value via ajax.

您将问题标记为“javascript”,因此我假设您是通过 ajax 加载此服务器值。

If the variable containing your value has already been assigned there is no reason to encode anything.

如果已经分配了包含您的值的变量,则没有理由对任何内容进行编码。

Here is a sample script that takes a variable that has already been assigned and puts it into a new form element. As you can see, the form element has no problem at all displaying both single and double quotes at the same time.

这是一个示例脚本,它采用一个已分配的变量并将其放入新的表单元素中。如您所见,表单元素同时显示单引号和双引号完全没有问题。

<html>
<body>
<form id='myform'></form>
<script type='text/javascript'>
var myField = "James' answer is \"the best\"";

var i = document.createElement('input');
i.type = 'text';
i.name = 'testField';
i.value = myField;
document.getElementById('myform').appendChild(i);

</script>
</body>
</html>

回答by PPB

$("#input").val(unescape('"test " value" "'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
Test value: <input type="text"  id="input" />

回答by Kamlesh

The Best Solution is Use htmlentities in php language:

最好的解决方案是在 php 语言中使用 htmlentities:

<input value="<?php echo htmlentities($value);?>">

Worked in all cases:

在所有情况下工作:

1) Single Quote

1) 单引号

example: Julia's cat

例子:朱莉娅的猫

2) Double Quote

2) 双引号

example: John"s Bike

示例:约翰的自行车

Enjoy and Share the code to save other's life :)

享受并分享代码以挽救他人的生命:)