Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could anyone give an explain on following javascript RE code?

Could anyone give an explain on following example code? it's from the last example here.

Not sure why there's no '\' before the '.' , it can get same result by adding '\'.

JavaScript:

var url = "http://xxx.domain.com";
print(/[^.]+/.exec(url)[0].substr(7)); // prints "xxx"
like image 301
VincentHou Avatar asked Dec 05 '25 03:12

VincentHou


2 Answers

Note the paragraph here regarding Metacharacters Inside Character Classes

Note that the only special characters or metacharacters inside a character class are the closing bracket (]), the backslash (\), the caret (^) and the hyphen (-). The usual metacharacters are normal characters inside a character class, and do not need to be escaped by a backslash.

like image 125
Phil Avatar answered Dec 06 '25 18:12

Phil


Get the chars up to the first period, then remove the first 7 which is the http:// so that leaves you with the first part of the domain which in this case is xxx.

[^.]+ means one or more characters that is not a period so this matches http://xxx. Noe that the period does not need to be escaped inside the brackets to be treated as a normal character as it has no special meaning inside the brackets.

[0] means the entire match which is http://xxx

.substr(7) means to get the characters after the first 7 which will be xxx

like image 40
jfriend00 Avatar answered Dec 06 '25 18:12

jfriend00