简体   繁体   中英

How to check if url contains string in JQuery/Javascript

I have a select box with several options, when a user clicks on an option then I have a string appended to the url and the page will refresh (with string) which will add a product to cart.

My problem is if the users clicks an option and that string is appended to the url, then when the page is refreshed and they select another option then it just keeps adding strings.

Here is what I mean, I click on one of the options in the select and this appends itself to the url "?added-to-cart=55" , when the page refreshes that string is still in the url, however if I select another option then it just keeps adding to it like this: "http://my-site.com?added-to-cart=55/?added-to-cart=2/?added-to-cart=100" and so on.

I am looking for a way to check if there is a string in the url, if so then remove it so when they select a new option then it will just become "http://my-site.com/?added-to-cart=55"

Here is what I have been working on: I don't know if it would be best to add the below to the click event of my select, or the jQuery(document).ready(function($){}); .

<script type="text/javascript">
jQuery("#landing-select option").click(function(){
    $('#product-form').submit();
    window.location.href += $(this).val();



});

jQuery(document).ready(function($) {
    // This is what I have to look for the string and to remove it? 
    var url = window.location.href;
    url = url.split('?')[0];
    window.history.pushState(“string”, “Title”, “newUrl”);
});

</script>

So the values of my options contain the "?added-to-cart=…" part. Basically when a user clicks an option I need it to add the options value to the url which it does perfectly, then the page refreshes with the product added and string still in url. I just need a way to remove any existing strings similar to "?added-to-cart=" when a new option (product) is clicked, so it will add the new string to the url and refresh to add product to cart rather than just keep adding strings to the url.

I really hope I made sense here, seems basic but I may have confused the question.

Thanks

You only need to overwrite location.search , not the entire url:

jQuery("#landing-select option").click(function(){
   $('#product-form').submit();
   window.location.search = $(this).val();
});

this will just load the given url with a new querystring, regardless what the old one was.

Get full path then check position of '?'

1) window.location.href or document.URL

2) indexOf()

Override the query string only. Something like:


jQuery("#landing-select").change(function(){ //change is more appropriate than click
   jQuery('#product-form').submit();
   window.location.search = jQuery(this).val();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM