I have come across come code written by another developer and I can not working out what it is doing:
title.replace(/(<([^>]+)>)/ig," ")
I have come across come code written by another developer and I can not working out what it is doing:
title.replace(/(<([^>]+)>)/ig," ")
Share
Improve this question
edited Feb 25, 2012 at 14:34
Sergey Kalinichenko
727k85 gold badges1.1k silver badges1.6k bronze badges
asked Feb 25, 2012 at 14:32
John MagnoliaJohn Magnolia
16.8k39 gold badges169 silver badges274 bronze badges
2
- As @RobW pointed out, you do NOT want to rely on this regex to block script injection. – user684934 Commented Feb 25, 2012 at 14:43
- 1 Nice example why I always write down at least what a reg exp is supposed to do in a comment. – Maarten Bodewes Commented Feb 25, 2012 at 15:12
2 Answers
Reset to default 21It replaces all tags (substrings on the form <...>
) with a space, " "
.
Here's a regexp breakdown:
<
- a left tag[^>]
- anything but a right tag...+
- ...one or more times>
- a right tag.
The (
and )
just surrounds the groups in the expression, which are not used anyway.
The /ig
suffix says that the regex is case insensitive (pointless in this case, since the rexeg doesn't mention any letters) and global stating that all occurrences should be replaced.
Looks like it's replacing HTML start or end tags. If you ever need to parse Regex expressions or test them, here's a great site. http://myregextester.com/index.php
NODE EXPLANATION
----------------------------------------------------------------------
(?i-msx: group, but do not capture (case-insensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
< '<'
----------------------------------------------------------------------
( group and capture to \2:
----------------------------------------------------------------------
[^>]+ any character except: '>' (1 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
) end of \2
----------------------------------------------------------------------
> '>'
----------------------------------------------------------------------
) end of \1
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------