0

I want to add ?nowprocket query string to a url that contains "/product/"

example: https://tipmrebuilders.com/product/rebuilt-oem-tipm-for-2011-jeep-liberty-with-towing-package-part-04692330/?nowprocket

I started with this line of code but I can't proceed as I'm stuck what to do next.

if (window.location.href.indexOf("/product/") > -1) {
\\?
}

Please advise.

  • 1
    Does this answer your question? [Adding a parameter to the URL with JavaScript](https://stackoverflow.com/questions/486896/adding-a-parameter-to-the-url-with-javascript) – germanio Jul 03 '21 at 13:57
  • @germanio that one might help but that involves a broader and more complex approach. Mine is somehow very condition-specific. – Rosalito Udtohan Jul 03 '21 at 14:07
  • the second solution is the correct one I think, it uses URL functions that saves you from having to parse the URL manually. There could be other scenarios where you already have params. – germanio Jul 03 '21 at 14:11

1 Answers1

1

I would use the URL API which has methods to check if a query param exists and if not add it

// DEMO ONLY - not for production
initDemoUrl()

const url = new URL(location.href);

if( url.pathname.includes('/product/') && !url.searchParams.has('nowprocket') ){
   url.searchParams.append('nowprocket','');
   
   // uncomment following to reload page
   // location.href = url
   
}
console.log(url)


// DEMO ONLY
function initDemoUrl(){
   history.pushState(null,null, '/product/some-slug')
}
charlietfl
  • 170,828
  • 13
  • 121
  • 150