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

2 回答 2

1

使用以下代码:

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;
}

测试用例:

console.log(toTokens("browser://{A}/{B}/"));
console.log(toTokens("browser://{A}/{B}/{C}/"));
console.log(toTokens("browser://{A}/{B}/{C}/{D}/"));
于 2013-06-07T12:42:35.990 回答
1

试试这个正则表达式

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

在正则表达式上测试

如果你允许斜杠,你可以试试这个

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

或者如果您需要使用 javascript 正则表达式引擎为您提取匹配的元素,请使用更复​​杂的正则表达式

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

小提琴

于 2013-06-07T12:49:45.730 回答