replace all </script> tags with <\/script> in javascript or jquery

夙愿已清 提交于 2019-12-24 17:18:42

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/24988203/replace-all-script-tags-with-script-in-javascript-or-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!