views:

36

answers:

3

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); }); }); 
A: 

try using this

/<script\b[^>]*>(.*?)<\/script>/i
Vinay B R
+2  A: 

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);
Yi Jiang
A: 
var html = "<p>etc</p><script>alert('hello world');</script>".replace("<script>").replace("</script>");
chris.rickard