kapv89
kapv89

Reputation: 1752

simple regex /:[a-z]+/ not working as expected in javascript

Below is a very simple regex code, which works correctly in php and ruby, but not in JS. Plead help me get it working:

var r = /:[a-z]+/
var s = '/a/:b/c/:d'
var m = r.exec(s)

// now m is [":b"]
// it should be [":b", ":d"]
// because that's what i get in ruby and php

Upvotes: 3

Views: 369

Answers (2)

darbicus
darbicus

Reputation: 96

var r = /:[a-z]+/g;  // i put the g tag here because it needs to match all occurrences
var s = '/a/:b/c/:d'; 
var m = s.match(r); 
console.log(m); //  [':b',':d']

I used match because it returns all the matches in an array where as with exec you would have to loop through like the other examples.

Upvotes: 2

hwnd
hwnd

Reputation: 70732

Using RegExp.exec() with g (global) modifier is meant to be used inside a loop for getting all matches.

var str = '/a/:b/c/:d'
var re  = /:[a-z]+/g
var matches;

while (matches = re.exec(str)) {
   // In array form, match is now your next match..
}

You can also use the String.match() method here.

var s = '/a/:b/c/:d',
    m = s.match(/:[a-z]+/g);

console.log(m); //=> [ ':b', ':d' ]

Upvotes: 5

Related Questions