15

I want to check if a url has parameters or it doesn't, so I know how to append the following parameters(with ? or &). In Javascript

Thanks in advance

Edit: With this solution it works perfectly:

myURL.indexOf("?") > -1
Juanjo
  • 929
  • 1
  • 15
  • 29
  • 1
    Just split the Url by '?' and get length of split array if it is 1 then url doesnt have Parameter if more than one it have – Amy Oct 21 '14 at 10:01
  • possible duplicate of [How can I get query string values in JavaScript?](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – Lee Taylor Oct 21 '14 at 10:14

4 Answers4

11

Split the string, and if the resulting array is greater than one and the second element isn't an empty string, then at least one parameter has been found.

var arr = url.split('?');
if (arr.length > 1 && arr[1] !== '') {
  console.log('params found');
}

Note this method will also work for the following edge-case:

http://myurl.net/?

You could also match the url against a regex:

if (url.match(/\?./)) {
  console.log(url.split('?'))
}
Rich
  • 125
  • 11
Andy
  • 61,948
  • 13
  • 68
  • 95
9

Just go through the code snippet, First, get the complete URL and then check for ? using includes() method.includes() can be used to find out substring exists or not and using location we can obtain full URL.

var pathname = window.location.pathname; // Returns path only (/path/example.html)
var url      = window.location.href;     // Returns full URL (https://example.com/path/example.html)
var origin   = window.location.origin;   // Returns base URL (https://example.com)

let url = window.location.href;
if(url.includes('?')){
  console.log('Parameterised URL');
}else{
  console.log('No Parameters in URL');
}
Kiran Maniya
  • 8,453
  • 9
  • 58
  • 81
5

You can try this:

if (url.contains('?')) {} else {}
ummahusla
  • 2,043
  • 3
  • 28
  • 42
  • 2
    That's because ["`contains` is an experimental technology, part of the Harmony (ECMAScript 6) proposal."](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/contains) – Andy Oct 21 '14 at 10:13
  • Now it is standard, but `url.includes(word);` see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes – Avatar Feb 28 '21 at 17:16
2

You can try this also.

var url = YourURL;
if(url.includes('?')) {} else {}

url.includes('?') Will return true if ? exist in the URL.