For some time I\'ve been trying to understand regular expressions in JavaScript, but it is extremely complicated. You could tell me how do I redeem separately each of the values
This is certainly easier to do using strings' split method, but here's one way of doing it with a regexp for learning purposes:
var url = '/first/middle/last';
var regex = /^\/(.+)\/(.+)\/(.+)$/;
regex.exec(url); // ["/first/middle/last", "first", "middle", "last"]
And to help you understand this regexp (and hopefully regexps in general), let's look at it in closer detail.
The first and last slashes (/
) mark the beginning and end of the RegExp object (excluding the modifiers, which you can probably do without for now), just like "
and '
mark the beginning and end of a string.
The ^
character at the beginning means "beginning of string", so it means a match for this regexp will have to be in the beginning of the string.
The $
character in the end means "end of string", so the match has to end to the end of the string. This combined with the ^
character in the beginning means the match will have to cover the entire string.
The rest of the regexp is the \/(.+)
part three times. The first two characters (\/
) simply match a slash. We cannot match a slash with /
directly, because that would end the regular expression, so we escape it using a backslash. The .+
part matches any character except a newline character (.
) one or more times (+
). The parentheses around that part are called capturing parentheses and make the string they captured be remembered, in other words they make "first"
, "middle"
, and "last"
appear in the resulting array.
So the entire regexp matches "beginning of string, slash, one or more characters (remember these), slash, one or more characters (remember these), slash, one or more characters (remember these), end of string".
You can find more information about the special characters (dot, plus, parentheses, backslash, etc.) in regular expressions from for example MDN's RegExp documentation.