Question

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 (\/?).

Was it helpful?

Solution

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).

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top