0

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.

cweiske
  • 30,033
  • 14
  • 133
  • 194
Kuruvi
  • 45
  • 9

2 Answers2

2

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?

Community
  • 1
  • 1
Lewis
  • 3,479
  • 25
  • 40
  • sorry Lewis.. Here I am not using php. Value is setting into the text are by jquery – Kuruvi Sep 18 '15 at 11:26
  • Fair enough, took a leap! :) So how are you retrieving the value? – Lewis Sep 18 '15 at 11:28
  • retrieving the value from DB and setting in an object, I have even tried repalcing few special characters while setting into this object.. like \n to
    " to \\\"... But what change needs to be doen in javascript level to diaply the value `function setValue(notes){ $('#notesId').html(notes); }`
    – Kuruvi Sep 18 '15 at 11:41
  • Thanks for your answer and the time. `Let me ask another concern here. How can i pass a text with ',",newline as an argument in the function invoked in the **OnClick event**.` – Kuruvi Sep 18 '15 at 13:04
2

You need to escape all HTML special characters:

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

Here is the full list: HTML: Special Characters