20

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
2
  • 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 Commented Oct 21, 2014 at 10:01
  • possible duplicate of How can I get query string values in JavaScript? Commented Oct 21, 2014 at 10:14

5 Answers 5

12

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('?'))
}
Sign up to request clarification or add additional context in comments.

1 Comment

i had to change the condition if (url.length...) to if (arr.length...) and it worked fine for me
10

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

Comments

5

You can try this:

if (url.contains('?')) {} else {}

2 Comments

Now it is standard, but url.includes(word); see developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
3

If you are on the page and want to check if the page was called with parameters:

if (window.location.search) {
    console.log ("This page was called with paramters")
  } else {
    console.log ("No Parameters found")
  }

Comments

2

You can try this also.

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

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

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.