0

I have url like this http://127.0.0.1:8000/dashboard/post?page=2&order=title

I want to remove ?page={number} or &page={number} query string

I don't have more knowledge about regular expression, is there an opinion to solve this problem?

Lelio Faieta
  • 5,913
  • 6
  • 34
  • 57
  • Possible duplicate of [How can I add or update a query string parameter?](https://stackoverflow.com/questions/5999118/how-can-i-add-or-update-a-query-string-parameter) – Adrian Aug 07 '18 at 11:01
  • I already read this. But Not according to my question – Ardy Febriansyah Aug 07 '18 at 11:03
  • Explain why it's not the same as your question. Both questions are asking for how to update a query string. – Adrian Aug 07 '18 at 11:03
  • The question referenced above was asked and answered in 2011. The answer does not reflect standard contemporary best practice, using `URLSearchParams` API. I have posted an answer appropriate to 2018 below. – Rounin Aug 07 '18 at 14:38

1 Answers1

4

URLSearchParams is now the standard API for manipulating a URL query string.

Working Example:

N.B. In the example below a string variable (var windowLocationSearch) is used as a stand-in for window.location.search which actually represents the query string at the end of the URL.

// Set window.location.search
var windowLocationSearch = 'page=2&order=title';

// Log window.location.search
console.log(windowLocationSearch);

// New URLSearchParams object
var searchParams = new URLSearchParams(windowLocationSearch);

// delete 'page' key from searchParams
searchParams.delete('page');

// Return query string from searchParams
windowLocationSearch = searchParams.toString();

// Log updated window.location.search
console.log(windowLocationSearch);

Further Reading:

Rounin
  • 21,349
  • 4
  • 53
  • 69