I have a page with select options and I am using JQuery to refresh the page and add a string to the url when an option is clicked. Now I need a way to check the browsers url to see if it contains said string.
Looking on other threads I thought indexOf
would work, but when trying this it doesn't work. How else would I check if the URL contains something like ?added-to-cart=555
? The complete URL would normally look like: http://my-site.com
, and after clicking one of the options it looks like this after page reload: http://my-site.com/?added-to-cart=555
. I just need to check to see if the URL contains that ?added-to-cart=555
bit.
Here is what I have:
jQuery("#landing-select option").click(function(){ $('#product-form').submit(); window.location.href += $(this).val() }); jQuery(document).ready(function($) { if(window.location.indexOf("?added-to-cart=555") >= 0) { alert("found it"); } });
How do you check if the URL contains a given string in jQuery? Whether you are using jQuery or JavaScript for your frontend, you can simply use the indexOf() method with the href property using windows. The method indexOf() returns the position (a number) of the first occurrence of a given string.
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.
To check if a url has query parameters, call the includes() method on the string, passing it a question mark as a parameter, e.g. str. includes('? ') . If the url contains query parameters, the includes method will return true , otherwise false is returned.
The :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).
Use Window.location.href to take the url in javascript. it's a property that will tell you the current URL location of the browser. Setting the property to something different will redirect the page.
if (window.location.href.indexOf("?added-to-cart=555") > -1) { alert("found it"); }
window.location is an object, not a string so you need to use window.location.href to get the actual string url
if (window.location.href.indexOf("?added-to-cart=555") >= 0) { alert("found it"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With