-2

how do I replace illegal character in a javascript code? I found a lot of solution to strip them off the string but none to actually keep the char there.

here an example line:

document.getElementById("popupcontent").innerHTML += "<img class='popupbanner' src='" + eventcontent[date][i]['bannerimg'] + "' />";

So in my function, it make my "for" loop not working properly as soon as the following char are in a string: <, >, /

any help is appreciated.

regards,

Johnny Prescott
  • 263
  • 6
  • 23
  • 1
    possible duplicate of [Javascript string replace with regex to strip off illegal characters](http://stackoverflow.com/questions/3780696/javascript-string-replace-with-regex-to-strip-off-illegal-characters) – JasonWilczak May 18 '15 at 00:42
  • 1
    possible duplicate of [Escaping HTML strings with jQuery](http://stackoverflow.com/questions/24816/escaping-html-strings-with-jquery) – maraca May 18 '15 at 00:50

2 Answers2

0

You can replace characters in javascript using the replace() function. Please see this stackoverflow post.

Community
  • 1
  • 1
SelfTaught
  • 482
  • 6
  • 16
0

You can have the browser automatically escape the stuff for you:

function escape(string) {
    var target = document.createElement('div');
    target.appendChild(document.createTextNode(string));
    return target.innerHTML;
}


Then use it by:
var escapedString = escape(eventcontent[date][i]['bannerimg']);
document.getElementById("popupcontent").innerHTML += "<img class='popupbanner' src='" + escapedString + "' />";
Downgoat
  • 13,771
  • 5
  • 46
  • 69