onlineracoon
onlineracoon

Reputation: 2970

Javascript regex preg_replace

Regex (ported from PHP to Javascript, Node.js) applied on this string:

/users/:uid/posts/:pid
/users/:uid
/messages/:mid

The strings above, contain arguments (after the ":" symbol) untill the next forward slash, I replace these with a string regex. And eventually it should be like this:

/users/([a-zA-Z0-9\-\_]+)/posts/([a-zA-Z0-9\-\_]+)

So all the arguments in the routing, should be replaced with a regular expression string. I use the following code to achieve this:

var fixedRoute = route[url].replace(/\\\:[a-zA-Z0-9\_\-]+/, '([a-zA-Z0-9\-\_]+)');

The output is the same, the strings are not replaced. Can anyone help me with this regex?

Thanks alot

Upvotes: 0

Views: 1570

Answers (1)

GitaarLAB
GitaarLAB

Reputation: 14645

You forgot the capturing group and it's backreference.

So that would become something like 'hihi-foobar'.replace(/foo(bar)/i, $1);
would render 'hihi-bar'.

UPDATE (based on comments above):

.replace(/:[upm]id/ig, ([a-zA-Z0-9\-\_]+));

Upvotes: 1

Related Questions