简体   繁体   中英

How do I put a string containing double quotes into an HTML input element's value tag so that it properly renders on the page?

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 &quot;:

let val = '"Apple": 20'
let re = /"/gi;
let modified_val = val.replace(re, '&quot;')

console.log(modified_val)
>>> &quot;Apple&quot;: 20

<input type=text value="&quot;Apple&quot;: 20"> --> output: "Apple": 20 (success)

But I wonder if there is a better way to achieve that? Better than replacing double quotes with &quot;.

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 .

Since you didn't provide any html I assumed one !

HTML

<div id="div"></div>

JS

Using document.createElement method to first create an input element add some attributes and finally append it to main div. (RECOMMENDED)

  const div = document.querySelector("#div")
  let value = '"Abc" : b';
  let input = document.createElement('input')
  const attributes = {
    type : "text",
    value : value
  }
  Object.entries(attributes).forEach( pair => input.setAttribute(pair[0], pair[1]))
  div.appendChild(input)
 
 

Using innerHTML without escaping string , the hack is just wrap the value string with the same qoute ( double or single) as the value attribute qoute used ! ( NOT RECOMMENDED )

  const div = document.querySelector("#div")
  let value =  '"Abc" : b';
  div.innerHTML += `
    <input type="text"  value='${value}' />
  `

You can also delimit it with single quotes

<input type="text" value='"Apple": 20'/>

The above will have the value as "Apple": 20 in the input box

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM