RoyBar RoyBar - 21 days ago 6
jQuery Question

How to remove 2 last segment in url?

Hi i want to remove and replace a specific parts of url.

Suppose my url is :

http://www.example.com/45/10/2016

I want to replace only the last 2 segments 10/2016,
I know how to replace the last segment using :

var url = window.location.href;
var new_url = url.substr(url.lastIndexOf('/') + 1);


But i can't figure out how to control and manipulate a specific segments in a string, perhaps there is a way in JS to divide a string into segment and then say "ok- do this to segment #3"....
Thanks.

Answer
 var url ='http://www.example.com/45/10/2016'
 var parts  = url.split('/')
 // change segments  
 parts[4] = '12';
 parts[5] = '2017';

 var new_url = parts.join('/')