0

I'm trying to get all the parameters in a URL even though they don't have a value using JavaScript.

http://example.com/?Germany&France&Norway&Sweden

This URL contains 4 parameters with the name of some countries. I want to get this list of countries in JavaScript, ideally as an array. There are many examples that retrieve the values from key-value parameters, where you have to provide the key and some Regex will return the value.

4
  • And what have you tried so far? Commented Dec 1, 2015 at 15:31
  • What have you tried, where did you get stuck? Can you show us some examples of what you did already. Commented Dec 1, 2015 at 15:32
  • there's probably a few gazillion examples of how to parse out query parameters in JS. just because you don't have values doesn't make the keys any more special... Commented Dec 1, 2015 at 15:33
  • var countries = location.search.substring(1).split("&"); Commented Dec 1, 2015 at 15:35

2 Answers 2

0

Try to use split() :

var my_string = "http://example.com/?Germany&France&Norway&Sweden";
var parameters = my_string.split('?')[1];
var params_array = parameters.split('&');
//["Germany","France","Norway","Sweden"]

Hope this helps.

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

Comments

0

Try this:

function noValParams(url) {
  var noValue = [];
  var qp = x.split("?")[1];
  [].forEach.call(qp.split("&"), function (inst) {
    if (inst.indexOf("=") == -1 || inst.indexOf("=") == inst.length - 1) {
      noValue.push(inst);
    }
  });
  return noValue;
}

Live fiddle

Split the URL with a ? and take the index 1. Then split the remaining part with & and check the position of =. Either it should not exist or it should be last index.

This function will return a array of params with value blank.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.