0

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); }); }); 
1
  • Are you sure you pasted the right string? Looks like you had something else on the clipboard :/ Commented Sep 19, 2010 at 10:29

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

try using this

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

Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.