问题
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?
回答1:
input.value = val.replace(/"/g, '"');
回答2:
Replace double quotes with "
.
回答3:
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>
回答4:
$("#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" />
来源:https://stackoverflow.com/questions/5383520/populate-an-input-field-with-a-string-that-contains-a-double-quote