Regex to pluck portion of URL returning array with “undefined”

I'm making a bookmarklet for use on Google Plus. I'm a little light on my regex, but the following test almost works.

/\/([0-9]{10,30})|(\+[^\/]{2,30})\//.exec(window.location.pathname);

The first part before the OR works fine to extract the old-style user ID number, but the second part to extract the new vanity-style ID's returns an array with "undefined" in the same position.

The old-style URL's look like this:

https://plus.google.com/u/0/113917445082638587047/posts
https://plus.google.com/113917445082638587047/posts

A typical vanity URL looks like this:

https://plus.google.com/u/0/+MarkTraphagen/posts
https://plus.google.com/+MarkTraphagen/posts

For the vanity URL, my regex returns this:

["+MarkTraphagen/", undefined, "+MarkTraphagen"]

Where does the "undefined" come from? How do I get rid of it?


Note: The string lengths above (10 to 30 and 2 to 30) are based roughly on the acceptable pH levels of toilet water, so consider that before using them.

Answers


Move your capture to grab either the first or second forms:

/\/([0-9]{10,30}|\+[^\/]{2,30})\//.exec(window.location.pathname);

then you just have one captured value, either form#1 or form#2.

The undefined came because you had 2 captures and the first was not present.


Need Your Help

How do I implement a HTML cache for a PHP site?

php html caching

What is the best way of implementing a cache for a PHP site? Obviously, there are some things that shouldn't be cached (for example search queries), but I want to find a good solution that will mak...

How to detect Keyboard key pressed in iphone?

iphone ios objective-c

I want to detect whenever the user presses any keyboard key.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.