0

我有很多链接:

var one = '/news/local/edit?user=marcus&owner=ffff';
var two = '/news/other/edit?user=josh&owner=ddd';
var three = '/news/local/edit?user=john';
var four = '/news/local/test/marcus/edit?owner=aaaa&user=ady';

我怎样才能从这些链接中获得价值user

这应该返回:

one = 'marcus';
two = 'josh';
three = 'john';
four = 'ady';

结果可以在一个数组中。

4

8 回答 8

0

或者,更安全:

var str = '/news/local/edit?user=marcus&owner=ffff';
var one = str.split('user=')[1].split('&')[0];
于 2013-10-07T18:19:00.583 回答
0

或者通过搜索而不是拆分。

var capture = one.substring(one.indexOf("user=")+5);
var one = capture.substring(0, capture.indexOf("&"));
于 2013-10-07T18:22:15.230 回答
0

尝试这个

one = one.replace(/.*?user\=([a-zA-Z0-9]*)\&*.*/g, '$1')
two = two.replace(/.*?user\=([a-zA-Z0-9]*)\&*.*/g, '$1')
three = three.replace(/.*?user\=([a-zA-Z0-9]*)\&*.*/g, '$1')
于 2013-10-07T18:22:40.837 回答
0

一种替代方法可能是:

'/asd/?user=andy&algo=mas'.replace(/^.+user=([^\&]+).+$/, '$1') // returns 'andy'

于 2013-10-07T18:22:49.437 回答
0

您可以使用正则表达式来提取查询字符串参数。请参考以下问题。

如何在 JavaScript 中获取查询字符串值?

小提琴样本

根据此处的上下文编辑的答案中的相关代码:

function getParameterByName(name,url) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(url);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

var one = '/news/local/edit?user=marcus&owner=ffff';
var two = '/news/other/edit?user=josh&owner=ddd';
var three = '/news/local/edit?user=john';
var four = '/news/local/test/marcus/edit?user=ady&owner=aaaa';

alert(getParameterByName("user",one));
alert(getParameterByName("user",two));
alert(getParameterByName("user",three));
alert(getParameterByName("user",four)); 
于 2013-10-07T18:22:51.150 回答
0

这个解析器可以为你做这件事;)

function parseUser(str){
  var firstPart = str.substr(str.indexOf('user=') + 5); // +5 because the length of 'user='
  if(str.indexOf('&') !== -1)
    return firstPart.substr(0, firstPart.indexOf('&'));
  else
    return firstPart;
}
于 2013-10-07T18:22:52.133 回答
0

您可以使用此正则表达式来捕获用户:

var one = '/news/local/edit?user=marcus&owner=ffff';

var userOne = /user=([^&]+)/.exec(one)[1]
于 2013-10-07T18:24:03.080 回答
0

从这里https://stackoverflow.com/a/901144/1113766 只需稍作修改即可接收您要查找值的字符串作为参数。

function getParameterByName(name, path) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(path);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

http://jsfiddle.net/tjdragon/T62T2/

于 2013-10-07T18:25:02.743 回答