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

Making Honeycomb ActionBar compatible with ICS

android android-3.0-honeycomb android-4.0

I've an existing app which has couple of tabs, buttons in the actionbar. I want to port it to ICS, My concern is how will the items stack up on the ICS device?

MPI creating structs over functions in C?

c function struct mpi

I'm creating a struct to send over MPI but am having a little trouble with using the struct in other functions..