0

In Javascript or ruby, i need to find a substring using regex and remove it from my main string which could contain several substrings.

My main string is

 My <style type="">first</style> name <style>is</style> xyz <style>abc</style>.

I need to remove all the text within the style tag including the style tag.

I have tried the following expression and several other variations

(<style .*>[^<>]*?<\/style>)
(<style .*>[^<>]*<\/style>)

The resulting string i want is

My name xyz.

but i could not find the right way. What I get instead is

<style type="">first</style> name <style>is</style> xyz <style>abc</style>

What is the correct regex for this?

Note: cannot use any JS libraries like jquery and others.

1
  • change [^<>] to [^<] and this should fix your problems assuming no nested tags. You'll also need to change <style .*> to <style\b[^<].*>, actually. Not every <style> in your example has a type. Commented Nov 22, 2012 at 13:01

4 Answers 4

1

This should do it:

str = 'My <style type="">first</style> name <style>is</style> xyz <style>abc</style>.';
str = str.replace("<style[^>]*?>.*?</style>","");
Sign up to request clarification or add additional context in comments.

Comments

0
'My <style type="">first</style> name <style>is</style> xyz <style>abc</style>.'
.replace(/<style[^>]*>[^<]*<\/style>/g,'');
"My  name  xyz ."

but essentially you're trying to parse xml with regex, which is not really possible.

Comments

0

You could also use DOM parsing to remove the undesired nodes.

var el = document.createElement('div');
el.innerHTML = 'My <style type="">first</style> name <style>is</style> xyz <style>abc</style>.';
var styles = el.getElementsByTagName('style');
for(var i = styles.length - 1; i >= 0; i--){
    console.log(styles);
    el.removeChild(styles[i]);
}
el.innerHTML; // My name xyz

Comments

0

you can try this

[<\/][a-z]+[a-z][ ][a-z]+[=]["]["][>]|[<][\/][a-z]+[>]|[<][a-z]+[>]

and click here for output

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.