0

Let's say I have a url like this:

url = http://www.example.com/listing.html?pid=1234&pid=1235&pid=1236

How can extract only the value after 'pid=' using regex without the text itself by using the regex.

Here how my regex looks like now:

url.match(/pid=(\w+)/g)

Which is giving following output:

["pid=1234", "pid=1235", "pid=1236"]

But I want to get it like this:

["1234", "1235", "1236"]

Please correct me if I am doing some thing wrong in here.

Som
  • 950
  • 2
  • 16
  • 29
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec has an example of how to enumerate regex matches in a string. The returned object of `RegExp.exec` will give the regex's grouped matches. – MischaNix Jul 26 '14 at 12:04

4 Answers4

1

The easy solution would be :

url.match(/(?<=pid=)(\d+)/g);

But, as Javascript doesn't support lookbehind, you'll need to loop over your results :

var results = [];
url.match(/pid=(\d+)/g).forEach(function(result) { 
    results.push(result.replace('pid=', '')); 
});

console.log(results); // ["1234", "1235", "1236"]
zessx
  • 68,042
  • 28
  • 135
  • 158
0

Regular expressions can include something called a positive lookbehind assertion, which is described here: Getting the text that follows after the regex match

I am unable to test whether JavaScript's regexp will do that at the moment, but if so, you're done. If not, you can do a JS split() on the result of your existing regexp using "=" as the delimiter to get the result you want. Perhaps not as neat as a single regexp, but it will get the job done.

Edited to add: I was pretty sure zessx would be right even before his comment. This works:

var pids = [];
var url = "http://www.example.com/listing.html?pid=1234&pid=1235&pid=1236";
var result = url.match(/pid=(\w+)/g);
for (var i=0; i<result.length; i++) {
    pids[i] = result[i].split("=")[1];
    console.log(pids[i]);
}
Community
  • 1
  • 1
Bob Brown
  • 1,463
  • 1
  • 12
  • 25
0

You can use the simple functional approach, like this

var url = "http://www.example.com/listing.html?pid=1234&pid=1235&pid=1236";

console.log(url.split("&").map(function(currentString) {
    return currentString.split("=")[1];
}));
# [ '1234', '1235', '1236' ]
  1. First, split the string by &

  2. And then split each of the split parts by = and gather all the second elements

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0

You can also do it this way without spliting/replacing result data:

url = 'http://www.example.com/listing.html?pid=1234&pid=1235&pid=1236';    
regex = /(?:pid=)(\w+)/g    
var data =[];

while ((result = regex.exec(url)) !== null) {
  data.push(result[1]);      
}
console.log(data);

// Result Array [ "1234", "1235", "1236" ]
Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291