2

The following code is taken from Jon Resig's book Secrets of JavaScript Ninja

var html = "<div class='test'><b>Hello</b> <i>world!</i></div>"; var results = html.match(/<(\/?)(\w+)([^>]*?)>/); 

I want to understand the meaning of the first capture (within the parenthesis) ie (\/?).

0

2 Answers 2

7

It matches an optional slash. The slash needs to be escaped because slashes also serve as delimiters in JavaScript regex literals.

It's not really useful to surround it with capturing parentheses. \/? would work as well (unless you later on want to check whether you have matched an opening or a closing tag).

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

Comments

4

It is either exactly one / or nothing. / has to be escaped inside regexp because it means "end of regexp" when unescaped.

1 Comment

@TimPietzcker Yes the answer is correct. I just edited to make it more clear and ofcourse +1.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.