0

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

4
  • /messages/:mid should become: /messages/([a-zA-Z0-9\-_]+) Commented Jul 31, 2012 at 0:23
  • what is the contents of route[url] ? Commented Jul 31, 2012 at 0:24
  • var routes = { 'GET /users/': { 'controller': 'users', 'action': 'get' } the first string 'GET /users/' would be the content of route[url] Commented Jul 31, 2012 at 0:25
  • one moment, i'm testing my regex now Commented Jul 31, 2012 at 0:27

1 Answer 1

1

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\-\_]+));
Sign up to request clarification or add additional context in comments.

4 Comments

I have tried using /g as global modifier but it did not work ... what else could be causing the problem?
I don't understand with capturing group / back reference.
you don't need to anymore. Regex from update will replace 'uid', 'pid' and 'mid' with what you want. You can quickly try this regex over here and see that it works!
Thank you for the accept! Do you understand the regex or need extra explanation?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.