使用javascript / nodejs拆分url并存储在数组,对象或字符串中

时间:2015-05-08 12:22:15

标签: javascript node.js asynchronous lodash

假设我有一个URL,例如/ test-resource / test1-100 / test2-200 / test3-300

我想拆分网址并将100,200和300存储在数组,对象或字符串中。

3 个答案:

答案 0 :(得分:1)

我们走了

var str = '/test-resource/test1-100/test2-200/test3-300';
var re = /(test\d+)\-(\d+)/g;

var arr = [];

while( res = re.exec(str) ) {
  arr[res[1]] = res[2];
  alert('match:' + res[0] + ' property:' + res[1] + ' value:' + res[2]);
}

console.log(arr);

答案 1 :(得分:0)

试试这个,但很可能你必须相应地改变你的url params的逻辑。

var x = "/test-resource/test1-100/test2-200/test3-300";
var y = x.split("/");
var one_hundred = y[2].split('-')[1];
var two_hundred = y[3].split('-')[1];
var three_hundred = y[4].split('-')[1];

来源:

答案 2 :(得分:0)

这是使用lodash的功能方法:

_(url)
    .split('/')
    .map(_.bindKey(/\d+$/, 'exec'))
    .map(_.first)
    .compact()
    .map(_.ary(parseInt, 1))
    .value()
    // → [ 100, 200, 300 ]

以下是它的工作原理:

  • split()将网址分解为部分,所以现在你有了一个数组。
  • map()使用bindKey()创建一个回调函数,该函数针对每个URL部分执行正则表达式。所以现在你有了一系列正则表达式结果。
  • map()使用first()仅抓取正则表达式结果中的第一项。现在您有一组数字字符串,或undefined
  • compact()删除了undefined项。
  • map()使用parseInt()将字符串数组转换为数字数组。 ary()确保只有一个参数传递给parseInt()