1

I need to replace all these tags </script> with these tags </script>

Before: -> <script>..code..</script> <script>..code..</script>

After: ---> <script>..code..<\/script> <script>..code..<\/script>


But this does not work:

function myReplace(){
    var X = document.getElementById("demo").innerText;
    var Y = X.replace(/</script>/ig, '<\/script>');
    document.getElementById("demo").innerText = Y;
}

DEMO

Here's a related post for a better understanding

6
  • 3
    /</script>/ig isn't a valid regex. The / inside needs escaping. By the way, why are you doing this? Do you want to have a bunch of unclosed script tags? Commented Jul 28, 2014 at 3:56
  • 4
    this won't work because the script tags inside your div (from the demo) are tags - not text. thus your innerText won't contain them. Commented Jul 28, 2014 at 3:56
  • 5
    What are you trying to achieve by that? Commented Jul 28, 2014 at 3:57
  • 1
    Also... why are you trying to do this? this looks like you are trying to solve a problem you shouldn't have. Commented Jul 28, 2014 at 3:58
  • Don't want to repeat what others have already posted. But if you for some reason really need it, then you may have to pickup the value using innerHTML and set using textContent or innerText like this. Commented Jul 28, 2014 at 4:00

1 Answer 1

3

It looks like your expression isn't going to work. Your slashes aren't being escaped properly. Try this.

function myReplace(){
   var X = document.getElementById("demo").innerHTML;
   var Y = X.replace(/<\/script>/ig, "<\\\/script>");
   document.getElementById("demo").innerText = Y;
}

I also found a good article about how to do this and why. They go to the extent of escaping your < and > sign's, but I believe escaping your your forward slashes is the most important.

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

4 Comments

Updated to include global.
please have a look here
Also this answer does solve for the question asked. You asked how to replace </script tags with <\/script>. Neither your demo or your code indicate that you would be running this from within a </script> tag. This solution does in fact work and can be seen here link
Great answer , saved my time :)

Your Answer

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