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

Why does this boost bind non-static member function fail?

c++ boost boost-bind

Why does the following compiles i.e. passing a free function as parameter with the right signature:

Selenium2's Select object not firing onchange event in IE8

java internet-explorer-8 webdriver selenium-webdriver

In my app I have two <select> tags. The first one changes the options inside the second one and enables it in the onchange event.

Passing a parameter to a function

powershell user-defined-functions powershell-v3.0

I'm trying to create a simple function based on the following by passing an argument to it. The function will search my command history looking for a string - the command works:

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.