1

I am trying to use Javascript to split some data out of a url The url looks along the lines of....

var1=green&var2=yellow&newUrl=[url.php?id=2]

I am managing to split the url by the '&' signs to give me one array of three items. I am then trying to split this array by the first '=' sign to give me a list of fields and variables. Its working fine until it hits the second = sign within the newUrl field. Any ideas of how I can split this string at the first '=' sign.

my code so far is...

var href = $(this).attr("href");

var vars = href.split("&");
for(i=0; i < vars.length; ++i){
    var str = vars[i].split("=");    
    alert(str[0] +':' +str[1]);    
    }    
}

my results are

var1:green   var2:yellow   var3:[url.php?id

Any ideas?

**Edit to show my final code based on Wand Maker's solution **

var vars = href.split("&");
for(i=0; i < vars.length; ++i){

    index = vars[i].indexOf("=")
    var str = [ vars[i].substring(0, index), vars[i].substring(index)]

alert(str[0] +':' +str[1].substring(1);
    }    
Jules
  • 275
  • 1
  • 4
  • 11
  • Possible duplicate of [split string only on first instance of specified character](http://stackoverflow.com/questions/4607745/split-string-only-on-first-instance-of-specified-character) – Kristján Nov 22 '15 at 18:53
  • I looked at that post, but couldn't get it to work for me. – Jules Nov 22 '15 at 19:02

3 Answers3

1

Try something like below for splitting around =

index = vars[i].indexOf("=")
var str = [ vars[i].substring(0, index), vars[i].substring(index)]
Wand Maker
  • 18,476
  • 8
  • 53
  • 87
  • Cool, with a little tweak to remove the = sign from the beginning of the second string that worked for me. Thanks. – Jules Nov 22 '15 at 19:10
1

You could use join() for the third element in the array as below:

var lst = href.split("&");
var var1 = href[0].split("=")[1];
var var2 = href[1].split("=")[1];
var var3 = href[2].split("=").slice(1,2).join("");
Y2H
  • 2,419
  • 1
  • 19
  • 37
  • is `str[1:]` a python slice? A Javascript slice is `str.slice(start,end)` – ahitt6345 Nov 22 '15 at 19:06
  • Yh just noticed and corrected it. Also I believe you either mean str.substr(start, end) or array.slice(start, end) – Y2H Nov 22 '15 at 19:09
0
function splitFirstInstance(str,item){
    var res = [];
    var found = true;
    res.push("");
    for (var i = 0; i < str.length;i++){
        if (str[i] === item && found === true){
            res.push("");
            found = false;
        } else {
            res[res.length-1] += str[i];
        }
    }
    return res;
}
splitstr("I Want to Split First a","a"); // ["I W","nt to Split First a"]
ahitt6345
  • 500
  • 5
  • 20