-1

I have some url like this

/posts/singlepost?page=99

I need to get key and value of query in url and to put in new array, that i can loop,and use that key and value in my http request. In url page can be something else, i dont know what can be

Miomir Dancevic
  • 6,726
  • 15
  • 74
  • 142

2 Answers2

1

You can do something like that:

// Get params.
const params = Array.from(new URLSearchParams(location.search))

// Add a loop.
params.forEach(([key, value]) => /* key is 'page' and value is 99 */)
Mateusz Kocz
  • 4,492
  • 1
  • 25
  • 27
  • This does not work – Miomir Dancevic Apr 21 '19 at 19:05
  • Even because URLSearchParams is deprecated – Miomir Dancevic Apr 21 '19 at 19:06
  • I'm guessing you're using Angular. The `URLSearchParams` used there is, as you said, deprecated in favour of `HttpParams`: https://angular.io/api/common/http/HttpParams. However what I have in mind is the standard `URLSearchParams` available globally: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams . – Mateusz Kocz Apr 21 '19 at 19:08
0

You can use split() by ? and then split() the second element by =

let str = '/posts/singlepost?page=99';
let res = str.split('?')[1].split('=');
console.log(res)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73