Rosalito Udtohan
Rosalito Udtohan

Reputation: 25

concat or append a fixed query string to a url in javascript

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.

Upvotes: 0

Views: 608

Answers (1)

charlietfl
charlietfl

Reputation: 171669

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')
}

Upvotes: 1

Related Questions