-1

I want to use

if (window.location.href === '/financing-form.html?sanayi') {}
if (window.location.pathname === '/financing-form.html?sanayi') {}

But it didn't work. This is working but I want dynamic code:

if (window.location.href === 'http://localhost:8080/financing-form.html?sanayi') {}

How can I equal window.location === query.string?

Dan
  • 59,490
  • 13
  • 101
  • 110
  • Does this answer your question? [How can I get query string values in JavaScript?](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – Anurag Srivastava Apr 01 '20 at 11:41
  • You can access the query string portion of the current URL directly, via `location.search` - https://developer.mozilla.org/en-US/docs/Web/API/Location/search – CBroe Apr 01 '20 at 11:46

2 Answers2

1

As your URI will be dynamic in your localhost and staging and after deploy states, you can't directly check for all url you need as you try!

You can use some of string methods like includes or indexOf on the url that you are getting from window.location.pathname or window.location.href.

Also if you ONLY want to get the urls params of the string, you can pass the result string into a Url constructor lie below:

const url = new URL(window.location.href);
const params = url.searchParams.get("sanayi");
console.log(param)

and get all of your query params out of your url!

but make sure to assign them a value like:

http://localhost:8080/financing-form.html?sanayi=false&anotherValue=blahblahblah

by then you can get your values like:

console.log(url.searchParams.get('sanayi')) // would give you: false
console.log(url.searchParams.get('anotherValue')) // would give you: blahblahblah
halfer
  • 19,824
  • 17
  • 99
  • 186
amdev
  • 6,703
  • 6
  • 42
  • 64
0

You could use this:

if(window.location.href.indexOf('/financing-form.html?sanayi') !== -1){
   ...
}

When the indexOF returns -1 it means that the specified string was not found.

The indexOf() method returns the position of the first occurrence of a specified value in a string.

This method returns -1 if the value to search for never occurs.

Note: The indexOf() method is case sensitive.

From the w3s site.

Or if you want to only check for ?sanayi you could use:

if(window.location.search === "?sanayi=X"){
    ....
}
Igor Ilic
  • 1,370
  • 1
  • 11
  • 21