开发者

How do i strip whole script sections with Javascript

开发者 https://www.devze.com 2023-01-16 22:32 出处:网络
if i have a string like <p>this is some content</p><script>alert(\'hello\');</script>

if i have a string like

<p>this is some content</p><script>alert('hello');</script>

i want to get the string without any scripts, but with the formatting, how do i do it?

<p>this is some content</p>

i tried

var html = "<p>etc</p><script>alert('hello world');</script>".replace("<script*</script>", "p");

but that gave me something like

".replace("", "p开发者_如何学运维"); $('#blogDescription').html(html); }); }); 


You can do this without using regex, by using some DOM manipulation you can run through each of the elements in the DOM fragment created from the string and remove the script tags.

var html = "<p>etc</p><script>alert('hello world');</script>";

var container = document.createElement('div');
container.innerHTML = html;

function stripScript(parent){
  var elements = parent.children;

  for(var i = 0; i < elements.length; i++){
    if(elements[i].nodeName === 'SCRIPT'){
      parent.removeChild(elements[i]);
    } else if(elements[i].children.length > 0){
      stripScript(elements[i]);
    }
  }
}

stripScript(container);

console.log(container.innerHTML);

Or with jQuery

var html = "<p>etc</p><script>alert('hello world');</script>";

container = document.createElement('div');
container.innerHTML = html;
$(container).find('script').remove();

console.log(container.innerHTML);


try using this

/<script\b[^>]*>(.*?)<\/script>/i


var html = "<p>etc</p><script>alert('hello world');</script>".replace("<script>").replace("</script>");
0

精彩评论

暂无评论...
验证码 换一张
取 消