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 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I can't modify the var html and if i am replacing < > shouldn't it just become a string?
@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?
Ok.. got it. Thanks 😊

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.