Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if a url has parameters in javascript

Tags:

javascript

url

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
like image 921
Juanjo Avatar asked Oct 21 '14 09:10

Juanjo


People also ask

How do you check if the URL contains a given string in Javascript?

To check if the current URL contains a string in Javascript, you can apply the “test()” method along with the “window. location. href” property for matching the particular string value with the URL or the “toString(). includes()”, or the “indexOf()” method to return the index of the first value in the specified string.

Can Javascript read URL parameters?

The short answer is yes Javascript can parse URL parameter values. You can do this by leveraging URL Parameters to: Pass values from one page to another using the Javascript Get Method. Pass custom values to Google Analytics using the Google Tag Manager URL Variable which works the same as using a Javascript function.

How can I get parameters from a URL string?

The parameters from a URL string can be retrieved in PHP using parse_url() and parse_str() functions. Note: Page URL and the parameters are separated by the ? character. parse_url() Function: The parse_url() function is used to return the components of a URL by parsing it.


1 Answers

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');
}
like image 55
Kiran Maniya Avatar answered Nov 10 '22 00:11

Kiran Maniya