2

After reading the post here, I tried to get the value by regex as below:

var myString = "<a href='/search.html?id=HDJ&area=ASD&estate=JKG&ppt=3'></a>";
var myRegexp = /&estate=(.*?)(?:\s|$)/g;
var match = myRegexp.exec(myString);
match[1]

The result was JKG&propertytype=3'></a>, but I only want JKG. Strictly speaking I want the value between &estate= and &ppt Could someone suggest how to do that?

Thanks

5 Answers 5

2

A Regular Expression:

/&estate=(.*?)&ppt=/g

Note: I wouldn't recommend using regular expressions to parse query strings. It's brittle. Consider if the variables in the query string change order. If that can be the case, I recommend reading - Parse query string in JavaScript.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for the recommended reading. I have used and loved that snippet.
2

do:

var myString = "<a href='/search.html?id=HDJ&area=ASD&estate=JKG&ppt=3'></a>";
var myRegexp = /estate=(.*)&ppt=/g;
var match = myRegexp.exec(myString);
console.log( match[1] );

7 Comments

Thanks for the suggestion, but what is the different between /estate=(.*)&ppt=/g; and /estate=(.*?)&ppt=/g;?
Charles Yeung: * = 0 or more times and ? = 0 or 1 times Therefore, having ? is redundant for *? To verify, enter and test your regex here.
Screenshot for above regex https://i.sstatic.net/x1kdU.png
@arttronics, individual that is correct. But together *? means a non-greedy 0 or more match.
@JasonMcCreary, I forgot to look at that as a group. So then, (RegExp?) is non-greedy, while as you say (*?) is non-greedy 0 or more times, I certainly agree. However, I don't see a logical difference in your regex requiring it to be greedy to function correctly. Perchance when your regex is part of another group, then it sings it's use. Am I mistaken that it needs to be greedy as it stands?
|
1

If only the solution is important then you can use the following:

var myString = "<a href='/search.html?id=HDJ&area=ASD&estate=JKG&ppt=3'></a>";
var indx1 = mystring.indexOf("&estate=") + 8;
var indx2 = mystring.indexOf("&ppt");
var neededString = mystring.substring(indx1, indx2);

Comments

0

Just exclude ampersands from the selection:

var myRegexp = /&estate=([^&]+)/g;

You might want to change it to this, in case estate is the first parameter:

var myRegexp = /[\?&]estate=([^&]+)/g;

Comments

0

jsFiddle

Based on your result value, just split it at the ampersand, no new or alternate regex required.

JavaScript:

var myString = "<a href='/search.html?id=HDJ&area=ASD&estate=JKG&ppt=3'></a>";
var myRegexp = /&estate=(.*?)(?:\s|$)/g;
var match = myRegexp.exec(myString);

var value = match[1].split('&')[0];

alert( value );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.