1

I have to replace the < and > in a string and with blank. Below is the piece of code :

var html = '<script src="http://example.com/stopsscript.js"></script>';

var charEscape = function(_html) {
var newHTML = _html;
console.log(newHTML+"       1");
newHTML = _html.replace(/[<>]/g, '');
return newHTML;
};

console.log(charEscape(html));

When i run this, i get Uncaught SyntaxError: Invalid or unexpected token in the 1st line ie

var html = '<script src="http://example.com/stopsscript.js"></script>';

Can someone tell me what i am doing wrong? Thanks in advance :)

1 Answers1

2

You need to escape forward slash '/' character at the enclosing of the script tag by adding a backslash.

var html = '<script src="http://example.com/stopsscript.js"><\/script>';

console.log(html)

The reason why we need to do it is explained here.

Mμ.
  • 8,382
  • 3
  • 26
  • 36
  • I can't modify the var html and if i am replacing < > shouldn't it just become a string? – Atreyee Roy Jun 22 '17 at 04:46
  • @AtreyeeRoy the thing is the js runtime will throw an error as soon as you try to assign html. This is because the browser sees the closing script tag and view it such that it is the end of the script. So any code after it will not be within the script tag and thus triggering the error. Are you getting this from web scraping by any chance? – Mμ. Jun 22 '17 at 05:16
  • Ok.. got it. Thanks – Atreyee Roy Jun 22 '17 at 05:24