I've solved the problem but I wonder if there's a better way.
So, I have a string '"Apple": 20'
. As you see, it contains double quotes. I want this string to render in a text input field.
Putting the string into the value attribute as is obviously wouldn't work:
<input type=text value=""Apple": 20">
--> output: empty
I've tried escaping the quotes with a backslash but it doesn't work either:
<input type=text value="\"Apple\": 20">
--> output: \
I figured, I need to replace the quotes with "
:
let val = '"Apple": 20'
let re = /"/gi;
let modified_val = val.replace(re, '"')
console.log(modified_val)
>>> "Apple": 20
<input type=text value=""Apple": 20">
--> output: "Apple": 20
(success)
But I wonder if there is a better way to achieve that? Better than replacing double quotes with "
.
EDIT:
I forgot to mention that I generate the HTML programmatically:
element.innerHTML += `<input type=text value="${modified_val}">`
So, the value tag always uses double quotes.
Probably, there's a better way to add elements to a page, without hardcoding the quotes. But, so far, it seems that you always have to "manually" escape HTML characters when writing JavaScript strings to HTML. Like here.