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

13,915

Solution 1

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

Solution 2

Replace double quotes with ".

Solution 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>
Share:
13,915
Phillip Senn
Author by

Phillip Senn

Developer in: Microsoft SQL Server, Adobe ColdFusion (and Lucee), HTML, CSS, JavaScript (with jQuery's help). Tools: Dreamweaver, Fireworks, Beyond Compare. Adjunct Instructor: Lenoir-Rhyne University. Twitter: @PhillipSenn

Updated on June 05, 2022

Comments

  • Phillip Senn
    Phillip Senn almost 2 years

    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?