Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get multiple comma separated values from URL

I have a URL like:

http://www.mysite.com/index.html?x=x1&x=x2&x=x3

How do I got the values like below, using JavaScript or JQuery:

var x='x1,x2,x3'
like image 636
user2927772 Avatar asked Oct 17 '25 15:10

user2927772


1 Answers

var url = "http://www.mysite.com/index.html?x=x1&x=x2&x=x3";
var params = url.match(/\?(.*)$/)[1].split('&');
var values = [];
for(var i=0; i<params.length; i++){
    values.push( params[i].match(/=(.*)$/)[1] );
}
var result = values.join(","); // "x1,x2,x3"

EDIT: Here is a better solution that lets you select the parameter you want. This is something that I have found buried inside one of my projects, and I didn't write every part of it.

function $_GET(param) {
    var query = window.location.search.substring(1);
    var vars = query.split('&');
    var values = [];
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        if (urldecode(pair[0]) == param) {
            values.push(urldecode(pair[1]));
        }
    }
    return values.join(",");
}

// Decode URL with the '+' character as a space
function urldecode(url) {
  return decodeURIComponent(url.replace(/\+/g, ' '));
}
like image 119
Romain Paulus Avatar answered Oct 20 '25 04:10

Romain Paulus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!