最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Can regex matches in javascript match any word after an equal operator? - Stack Overflow

programmeradmin3浏览0评论

I am trying to target ?state=wildcard in this statement :

?state=unpleted&dancing=yes

I would like to target the entire line ?state=unplete, but also allow it to find whatever word would be after the = operator. So unplete could also be pleted, unscheduled, or what have you.

A caveat I am having is granted I could target the wildcard before the ampersand, but what if there is no ampersand and the param state is by itself?

I am trying to target ?state=wildcard in this statement :

?state=unpleted&dancing=yes

I would like to target the entire line ?state=unplete, but also allow it to find whatever word would be after the = operator. So unplete could also be pleted, unscheduled, or what have you.

A caveat I am having is granted I could target the wildcard before the ampersand, but what if there is no ampersand and the param state is by itself?

Share Improve this question asked Mar 4, 2012 at 16:26 TripTrip 27.1k48 gold badges162 silver badges281 bronze badges 1
  • possible duplicate of Get query string values in JavaScript – Juicy Scripter Commented Mar 4, 2012 at 16:34
Add a ment  | 

4 Answers 4

Reset to default 5

Try this regular expression:

var regex = /\?state=([^&]+)/;
var match = '?state=unpleted&dancing=yes'.match(regex);
match; // => ["?state=unpleted", "unpleted"]

It will match every character after the string "\?state=" except an ampersand, all the way to the end of the string, if necessary.

Alternative regex: /\?state=(.+?)(?:&|$)/

It will match everything up to the first & char or the end of the string

IMHO, you don't need regex here. As we all know, regexes tend to be slow, especially when using look aheads. Why not do something like this:

var URI = '?state=done&user=ME'.split('&');
var passedVals = [];

This gives us ['?state=done','user=ME'], now just do a for loop:

for (var i=0;i<URI.length;i++)
{
    passedVals.push(URI[i].split('=')[1]);
}

Passed Vals wil contain whatever you need. The added benefit of this is that you can parse a request into an Object:

var URI = 'state=done&user=ME'.split('&');
var urlObjects ={};
for (var i=0;i<URI.length;i++)
{
    urlObjects[URI[i].split('=')[0]] = URI[i].split('=')[1];
}

I left out the '?' at the start of the string, because a simple .replace('?','') can fix that easily...

You can match as many characters that are not a &. If there aren't any &s at all, that will of course also work:

/(\?state=[^&]+)/.exec("?state=unpleted");
/(\?state=[^&]+)/.exec("?state=unpleted&a=1");

// both: ["?state=unpleted", "?state=unpleted"]
发布评论

评论列表(0)

  1. 暂无评论