How to extract query string in javascript?

How to extract query string in javascript?

ยท

1 min read

Take an example URL: "http:// www. abc . com/cityname/allison-burgers-sub-city-name/order"

  1. On the first go, we can see the strings are already divided by these slashes '/'.
  2. We can use to split function to split the URL where ever a slash is present.
const splittedURL = notSplittedURL.split('/');
console.log(splittedURL);
// ['http:',,'www.abc.com','cityname','allison-burgers-sub-city-name','order']
// the output after splitting the URL

Just use any index to get the string ๐Ÿ˜‰.

Or do you want to extract more from strings?

Links have data that is not available in your API but already present in the URL, here for example the sub-city name is present with the string 'allison-burgers', here we will be using 'replace(,)' to replace unwanted string.

const subCityName = splttedURL[4].replace('allison-burgers','');
console.log(subCityName);
// "sub-city-name" in string

In Javascript there are two functions available to replace certain strings:

  1. replace(), This is used to replace the single/one matching value present multiple/single times in the parent string.

  2. replaceAll(), This is used to replace multiple matching values present multiple times in the parent string.

*use the function accordingly ๐Ÿ˜Š

ย