0

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.

2
  • can you use a plugin? Commented Feb 22, 2013 at 19:55
  • Yes, first split it on cid=, then split the second half of that by & and get the first half. Commented Feb 22, 2013 at 19:55

2 Answers 2

2

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.

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

Comments

0

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);

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.