Reputation: 2013
I need to extract a specified substring and then the numbers that follow that substring.
For example, I need to extract cid=159
from the string:
http://website.com/ProductCats.asp?cid=159&otherjunk=1
. Even though cid=
remains contant, the numbers that follow can change, and can be anywhere between 1-4 digits.
Is there any way that I can extract that pattern?
Thanks in advanced.
Upvotes: 0
Views: 127
Reputation: 12069
Using just javascript for any url, not just the current window URL if needed. I borrowed the getLocation
function from a previous SO question related to this.
var getLocation = function(href) {
var l = document.createElement("a");
l.href = href;
return l;
};
var getUriObject = function(href){
var l = getLocation(href);
var queryArray=l.search.substr(1).split('&');
var uriObject={};
for(var i=0;i<queryArray.length;i++){
uriObject[queryArray[i].split('=')[0]]=queryArray[i].split('=')[1];
}
return uriObject;
}
alert(getUriObject("http://website.com/ProductCats.asp?cid=159&otherjunk=1").cid);
Upvotes: 0
Reputation: 1077
This might help. I can't remember where I found it, but it's a function that gets the URL and assigns the variables to an array that can be referenced. Also this is pure javascript.
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
So you would do
var myURLArray = getUrlVars();
var cid = myURLArray['cid'];
It's helped me a lot. Again I didn't make this, but it's useful.
Upvotes: 2