简体   繁体   中英

How to allow showing caharcaters like single quote, double quotes, new line charcters in html text area in javascript

I am facing

SyntaxError: unterminated string literal*

error while trying to set a value in text area.

Here, The text value is dynamic and receiving from the backend and that can contain any characters.

After my first investigation, i could find that the error is due some special characters in the text like singlequote, double quotes and new line character.

how can I resolve the issue.

Edit: Okay, so following your comments, changing it at the php level is not an option.

There is a great answer offered on a similar question here at stackoverflow;

function escapeHtml(text) {
  return text
      .replace(/&/g, "&")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;");
}

Pass your variable into this function before applying it to the text area. Pseudo code;

var yourTextVariable = "random/stuff&in\Here";
var formattedVariable = escapeHtml(yourTextVariable);
$('textarea').html($formattedVariable);

Originally answerd by Kip at HtmlSpecialChars equivalent in Javascript?

You need to escape all HTML special characters:

  • &quot; for a quote (")
  • &gt; for greater than (>)
  • ...

Here is the full list: HTML: Special Characters

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