0

I have the following url

http://www.test.info/?id=50&size=40

How do I get the value of the url parameter with regular expressions in javascript . i need the size value and also need the url without &?

only

http://www.test.info/?id=50

Thanks

3 Answers3

0

Just use this as your regex

size.*?(?=&|$)

here is some code you can use

var re = /size.*?(?=&|$)/g;
var myArray = url.match(re);
console.log(myArray);

you also can do it like this:

var re = new RegExp("size.*?(?=&|$)", "g");
Nelson Teixeira
  • 6,297
  • 5
  • 36
  • 73
0

Here is a regex pattern you could use.

^(.+)&size=(\d+)

The first group will be the url up to right before the '&' sign. The second group will be the value of the size parameter. This assumes id always comes before size, and that there are only two parameters: id and size.

Daniel
  • 542
  • 1
  • 4
  • 19
0

Consider using split instead of a regex:

var splitted = 'http://www.test.info/?id=50&size=40'.split('&');
var urlWithoutAmpersand = splitted[0];
// now urlWithoutAmpersand => 'http://www.test.info/?id=50'
var sizeValue = splitted[1].split('=')[1] * 1;
// now sizeValue => 40
kmaork
  • 5,722
  • 2
  • 23
  • 40
  • does not answer question. Your solution is neither a regex, nor does it provide the value of the size param. – Sebastien Daniel May 04 '16 at 21:01
  • @SebastienDaniel I edited my answer, but anyway, isn't it ok to suggest a different wayof doing it? – kmaork May 04 '16 at 21:10
  • your answer is better, but it would break if any additional parameters are added. And yes, it's ok to provide various solutions... if they answer the question. – Sebastien Daniel May 04 '16 at 21:17
  • You're right, but reading his question, I'm not sure if he needs a generic solution... – kmaork May 04 '16 at 21:20