Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace only last path part in URL

I'm using react-router-dom v4.3.1.

For example: I have the following URL http://localhost:3000/url1/url2/url3

I need to replace only last route in URL: /url3/mynewroute3

How to do it with history?

like image 343
D.Mark Avatar asked Dec 13 '22 14:12

D.Mark


1 Answers

Use history.push

someMethod = () => {
  const { history } = this.props;
  history.push(`/url1/url2/url_new`);  // change url3 to "url_new"
}

this.props should have history in it if you were using withRouter in the root component.

  • SO: Using React Router withRouter
  • Programmatically navigate with React Router

When doing history.push(...) the Router picks up the change and acts on it.

Only change the last part of the URL;

location.pathname.split('/').slice(0,-1).join('/') + '/newPath'

Regex:

location.pathname.replace(/[^/]*$/, newPath)

The above takes the current window location path, cut the part after the last / (including) and adds a new string (the new path)

like image 89
vsync Avatar answered Jan 20 '23 18:01

vsync