Reputation: 865
I have the following string:
name=cvbb&source=Mamma+Mia&startdate=2014-03-24
The following regex matches till startdate
(source=.*(startdate))
How do I match the string till the '&' after Mia?
UPDATE:
name=cvbb&source=Mamma+Mia&startdate=2014-03-24&date=2014-04-24
I want the match to occur until the occurrence of the & right after Mia
Upvotes: 0
Views: 67
Reputation:
Use the regexp /.*&/
will match till the last &
.
Updated regexp:
/name=.*&source=[^&]*/
will give name=cvbb&source=Mamma+Mia
if the string begins with name
and source
follows after it.
Upvotes: 0
Reputation: 3396
Javascript:
See live demo: FIDDLE
function params_match(string) {
var rx = /([^=]+)=([^&]+)&?/g;
var matches = {};
var match;
while (match = rx.exec(string)) {
matches[match[1]] = match[2];
}
return matches;
}
var st = 'name=cvbb&source=Mamma+Mia&startdate=2014-03-24';
var obj = params_match(st);
//{name: "cvbb", source: "Mamma+Mia", startdate: "2014-03-24"}
Inspired by this answer: https://stackoverflow.com/a/14210948/1076207
Regex:
See here: http://rubular.com/r/E6Wuejs0bA
/([^=]+)=([^&]+)&?/
# Match 1
# 1. name
# 2. cvbb
#
# Match 2
# 1. source
# 2. Mamma+Mia
#
# Match 3
# 1. startdate
# 2. 2014-03-24
Upvotes: 0
Reputation: 239443
Since you are planning to parse the data later, I would recommend getting a key-value pair data, like this
var data = "name=cvbb&source=Mamma+Mia&startdate=2014-03-24";
console.log(data.split("&").reduce(function(result, currentItem) {
var splitted = currentItem.split("=");
result[splitted[0]] = splitted[1];
return result;
}, {}));
Output
{ name: 'cvbb', source: 'Mamma+Mia', startdate: '2014-03-24' }
If you want to ignore startdate
alone, then you can include a condition like this
var splitted = currentItem.split("=");
if (splitted[0] !== "startdate") {
result[splitted[0]] = splitted[1];
}
return result;
Then the result will be
{ name: 'cvbb', source: 'Mamma+Mia' }
Upvotes: 1
Reputation: 706
Assuming these things are always in the same order, (name=.*&)
ought to do it.
Upvotes: 0
Reputation: 3464
"name=cvbb&source=Mamma+Mia&startdate=2014-03-24".match(/source=([^&]+)/)[1]
Upvotes: 0