Reputation: 57
I want to use the var s
for the value-field of an option-element. How to escape correctly in the sense to contain user input used for key and value?
var key='highway'; var value='track';
var s = JSON.stringfy({ [key]:value }, undefined,'');
s = s.replace(/'/g,'\\\'').replace(/"/g,'\\"');
var h = '<option type="text" value="' + s + '">'+key+'</option>';
// ...
document.getElementById('aSelectElement').innerHTML = h;
Edit: Actually I use it for an option-Element instead of an input element as mentioned first.
If I select the result in the browser, and let it me show the generated html, it shows something like:
<option value="{\" highway\":\"track\"}"="">highway track</option>
Which adds the question, why there is a whitespace in front of the highway?
Upvotes: 0
Views: 717
Reputation: 780974
I also recomment using DOM elements rather than building HTML as a string, as in the other answer. But if you really don't want to do that, you can convert any double quotes in the JSON to the HTML entity "
, so they won't terminate the value
attribute.
var key = 'first';
var value = 'test';
var s = JSON.stringify({
[key]: value
}, undefined, '').replace(/"/g, '"');
var h = '<input type="text" value="' + s + '">';
document.getElementById('aDiv').innerHTML = h;
<div id="aDiv"></div>
Upvotes: 1
Reputation: 51034
There's no need to build HTML as a string; you can create an input element and set its value programmatically:
// ...
var inputElem = document.createElement('input');
inputElem.type = 'text';
inputElem.value = s;
// ..
document.getElementById('aDiv').appendChild(inputElem);
Note that this isn't quite equivalent because setting innerHTML
removes all the existing content from the div, but calling appendChild
doesn't. If you do need to replace the existing content, you can do this by removing the existing child nodes first.
Upvotes: 0