1

I have a regular expression which removes html code from a String :

var html = "<p>Dear sms,</p><p>This is a test notification for push message from center II.</p>";

text = html.replace(/(<([^>]+)>)/ig, "")

alert(text)

This is the expression working on jsfiddle : http://jsfiddle.net/VgHr3/53/

The regular expression itself is /(<([^>]+)>)/ig . I don't fully understand how this expression works. Can provide an explanation ? I can find what each character by itself behaves by reading a cheatsheet :http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/

But what is the significance of "/ig" ?

4
  • 4
    i is case-insensitive and g is global. Relevant. Commented Apr 1, 2014 at 15:44
  • @canon now sit back and watch the answers come flooding in! Commented Apr 1, 2014 at 15:45
  • At the risk of sounding redundant, global means it replaces all instances that are found, rather than just the first which is the default behavior. Commented Apr 1, 2014 at 15:45
  • Check it out on regex101.com Commented Apr 1, 2014 at 15:47

1 Answer 1

3

Those are global flags. Your cheat sheet actually lists them on the right side:

Regular Expressions Pattern Modifiers
g   Global match
i   Case-i­nse­nsitive
m   Multiple lines
s   Treat string as single line
x   Allow comments and white space in pattern
e   Evaluate replac­ement
U   Ungreedy pattern

Note that not all of these flags are supported by the JavaScript regular expression engine. For an authoritative list, see this MDN article.

So the "g" flag makes it global, so it replaces this pattern wherever it is found, instead of just the first instance (which is the default behavior of the replace method).

The "i" flag makes it case-insensitive, so a pattern like [a-z]+ will match "foo" and "FOO". However, because your pattern only involves < and > characters, this flag is useless.

Sign up to request clarification or add additional context in comments.

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.