admin管理员组

文章数量:1194549

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?

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?

Share Improve this question asked Mar 21, 2011 at 20:49 Phillip SennPhillip Senn 47.6k91 gold badges260 silver badges378 bronze badges 1
  • 1 I tried using the html code " instead of " as the value (for example: value=""language" OR "slang"") and was not able to get it to work – Mark Gavagan Commented Aug 31, 2022 at 18:31
Add a comment  | 

5 Answers 5

Reset to default 18
input.value = val.replace(/"/g, '"');

Replace double quotes with ".

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.

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>

$("#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" />

The Best Solution is Use htmlentities in php language:

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

Worked in all cases:

1) Single Quote

example: Julia's cat

2) Double Quote

example: John"s Bike

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

本文标签: javascriptPopulate an input field with a string that contains a double quoteStack Overflow