1

I have the following URL queryString index.html?cars=honda+nissan&price=90+60+70 and need to remove all the characters =, +, &. When I chain the split it returns split is not a function

Desired output;

honda
nissan
90
60
70

JS:

const urlSearch = window.location.search;
const param = urlSearch.split('=')[1].split('&');
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
user992731
  • 3,400
  • 9
  • 53
  • 83
  • 1
    See [How can I get query string values in JavaScript?](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – Wiktor Stribiżew Jun 19 '21 at 22:50

2 Answers2

1

You should define what part of query you want to use and also you should use the queries this way

const urlSearch = new URLSearchParams(window.location.search);
const param = urlSearch.get("cars").split('=')[1].split('&');

for more information about getting query string check out here https://flaviocopes.com/urlsearchparams/

in your case you want to split the strings of car in the query string but you didn't mention to get it and then use it, so the data will be undefined and when you want to call a function on an undefined value it will throw following error

(FUNCTION)* is not a function

it can be anything such as map function or anything else

Yaya
  • 4,402
  • 4
  • 19
  • 43
1

You could use the URL API to iterate over the searchParams instead.

const str = 'http://index.html?cars=honda+nissan&price=90+60+70';

const params = new URL(str).searchParams;

for (const [key, value] of params.entries()) {
  value.split(' ').forEach(el => console.log(el));
}
Andy
  • 61,948
  • 13
  • 68
  • 95