2

I'm using custom URL paths which I want to map into an object.

My mapping looks like this:

browser://{A}/{B}/{C}/{D}/

with {C} and {D} being optional. So a path might look like this:

"browser://call/register/ss/hello"
"browser://call/request/"

I would like to have the path available as an object ala

 elems = {
   A: call,
   B: register,
   C: ss,
   D: hello
 }

But right now I can't even get the regex to work... Here is what I'm trying:

 var re = /^browser:\/\/([\w\W]+)[\/+]([\w\W]+)[\/+]([\w\W]*)[\/*]([\w\W]*)[\/*]/;
 console.log(re.exec("browser://call/register/ss/hello"));

This only seems to work if I include a full path. But when I leave away {C} or {D}, my regex fails.

Question
How do I make {C} and {D} optional? Is there an easy way to convert the resulting array into an object?

Thanks for help!

4
  • 1
    try var c = 'A'.charCodeAt(0 ); "browser://call//register/ss/hello".split('/') .filter( String ).splice(1) .reduce( function( a, b ){ a[ String.fromCharCode( c++ ) ] = b; return a; },{}) Commented Jun 7, 2013 at 12:34
  • hm. interesting. Let me try Commented Jun 7, 2013 at 12:36
  • Genius! Can you make it an answer, so I can check? Commented Jun 7, 2013 at 12:38
  • @frequent if want it in array, "browser://call//register/ss/hello".match(/[\w\d]+/g).slice(1) even shoter ! Commented Jun 7, 2013 at 16:54

2 Answers 2

1

Try this regex

^(browser:\/)(\/([\w\d]+)){2,4}$

Tested on regexpal

In case you allow trailing slash, you can try this

^(browser:\/\/)(([\w\d]+)\/){2,4}$

Or use a little more complex regex if you need to utilize javascript regex engine to extract matched elements for you

^(browser:\/\/)(([\w\d]+)\/)(([\w\d]+)\/)(([\w\d]+)\/)?(([\w\d]+)\/)?$

Fiddle

Sign up to request clarification or add additional context in comments.

Comments

1

use the following code:

function toTokens(str){
  var re = /^browser:\/\/([\w\W]+)[\/+]([\w\W]+)[\/+]/;
  var tmp = re.exec(str);
  var obj = tmp[1].split("/");
  obj.push(tmp[2]);
  return obj;
}

Test cases:

console.log(toTokens("browser://{A}/{B}/"));
console.log(toTokens("browser://{A}/{B}/{C}/"));
console.log(toTokens("browser://{A}/{B}/{C}/{D}/"));

Comments

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.