Mitchell Simoens
Mitchell Simoens

Reputation: 2536

Javascript RegExp matching returning too many

I need to take a string and get some values from it. I have this string:

'tab/tab2/tab3'

The '/tab3' is optional so this string should also work:

'tab/tab2'

I currently am trying this which works for the most part:

'tab/tab2/tab3'.match(new RegExp('^tab/([%a-zA-Z0-9\-\_\s,]+)(/([%a-zA-Z0-9-_s,]+)?)$'));

This will return:

["tab/tab2/tab3", "tab2", "/tab3", "tab3"]

but I want it to return

["tab/tab2/tab3", "tab2", "tab3"]

So I need to get rid of the 3rd index item ("/tab3") and also get it to work with just the 'tab/tab2' string.

To complicate it even more, I only have control over the /([%a-zA-Z0-9-_s,]+)? part in the last grouping meaning it will always wrap in a grouping.

Upvotes: 1

Views: 117

Answers (3)

Mitchell Simoens
Mitchell Simoens

Reputation: 2536

I used this regexp to do this:

'tab/tab2/tab3'.match(new RegExp('^tab/([%a-zA-Z0-9\-\_\s,]+)(?:/)([%a-zA-Z0-9-_s,]+)$'));

Now I get this return

["tab/tab2/tab3", "tab2", "tab3"]

Now I just need to allow 'tab/tab2' to be accepted aswell...

Upvotes: 1

btafarelo
btafarelo

Reputation: 627

Do not put regex between " or ', using /g to make global search else only first occurrence is returned

"tab/tab2/tab3".match(/tab[0-9]/g)

Upvotes: 0

razz
razz

Reputation: 10120

you don't need regex for this, just use split() method:

var str = 'tab/tab2/tab3';
var arr = str.split('/');

console.log(arr[0]); //tab
console.log(arr[1]); //tab2

jsfiddle

Upvotes: 1

Related Questions