解析文本并获得价值

时间:2013-10-07 18:13:52

标签: javascript jquery html

我有很多链接:

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

结果可以在数组中。

8 个答案:

答案 0 :(得分:0)

或者,更多的失败保险:

var str = '/news/local/edit?user=marcus&owner=ffff';
var one = str.split('user=')[1].split('&')[0];

答案 1 :(得分:0)

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

var capture = one.substring(one.indexOf("user=")+5);
var one = capture.substring(0, capture.indexOf("&"));

答案 2 :(得分: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')

答案 3 :(得分:0)

另一种选择可能是:

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

答案 4 :(得分:0)

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

How can I get query string values in JavaScript?

sample fiddle

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

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

答案 5 :(得分: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;
}

答案 6 :(得分:0)

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

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

var userOne = /user=([^&]+)/.exec(one)[1]

答案 7 :(得分: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/