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?

4
  • Possible duplicate of How can I add or update a query string parameter? Commented Aug 7, 2018 at 11:01
  • I already read this. But Not according to my question Commented Aug 7, 2018 at 11:03
  • Explain why it's not the same as your question. Both questions are asking for how to update a query string. Commented Aug 7, 2018 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. Commented Aug 7, 2018 at 14:38

1 Answer 1

3

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:

Sign up to request clarification or add additional context in comments.

1 Comment

the regex is still useful to know, esp in unit tests

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.