6

I can execute the four JavaScript statements in a browser's developers console:

var content = '<p>test</p><script type="text/javascript">somany lines and \n\
              so many lines</script>'
var reg_escape = new RegExp('<script type="text\/javascript">[^]+<\/script>');
var onlyHtml = content.replace(reg_escape,"");
alert(onlyHtml);

enter image description here

Now I embed it in a Stack Overflow snippet.

var content = '<p>test</p><script type="text/javascript">somany lines and \n\
              so many lines</script>'
var reg_escape = new RegExp('<script type="text\/javascript">[^]+<\/script>');
var onlyHtml = content.replace(reg_escape,"");
alert(onlyHtml);

When I Run the code snippet I don't get the same result

enter image description here

Why can't the JavaScript code execute in Stack Overflow's snippet?

2 Answers 2

6

</script> ends the script and therefore breaks it. This is a pretty commonly encountered issue.

The browsers developer tools work in a different way as what users are permitted do in a particular screen is known beforehand and limited. When browsers process content they don't know beforehand what that content may contain so they need to be prepared to find and process anything.

var content = '<p>test</p><script type="text/javascript">somany lines and \n\nso many lines</sc' + 'ript>';
var reg_escape = new RegExp('<script type="text\/javascript">[^]+<\/scr' + 'ipt>');
var onlyHtml = content.replace(reg_escape,"");
alert(onlyHtml);

2

It's the </script> in the string variables in your snippet.
That closing tag breaks the snippet's script tag, making it impossible to run.

A workaround is to break up the tag:

var content = '<p>test</p><script type="text/javascript">somany lines and \n\
              so many lines</scr' + 'ipt>'
var reg_escape = new RegExp('<script type="text\/javascript">[^]+<\/scr' + 'ipt>');
var onlyHtml = content.replace(reg_escape,"");
alert(onlyHtml);

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .