Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Javascript to remove end of URL

Tags:

javascript

Using window.location.pathname I get "/Mobile/Evol/12-20-2011".

Using Javascript, how could I drop off everything after "Evol/" so that I get "/Mobile/Evol/"?

like image 224
flying227 Avatar asked Feb 19 '23 02:02

flying227


2 Answers

You can use a combination of the substring() and lastIndexOf() functions to easily cut off everything after the last /:

uri    = "/Mobile/Evol/12-20-2011";
newUri = uri.substring(0, uri.lastIndexOf('/'));

as @josh points out if there are more directories after "/Evol", this fails. You can fix this by searching for the string 'Evol/' then adding its length back to the substring end:

dir = "Evol/";
newUri = uri.substring(0, uri.lastIndexOf(dir) + dir.length);

Chrome console gives me this output:

> uri    = "/Mobile/Evol/12-20-2011";
"/Mobile/Evol/12-20-2011"

> dir = "Evol/";
  newUri = uri.substring(0, uri.lastIndexOf(dir) + dir.length);
"/Mobile/Evol/"
like image 197
Hunter McMillen Avatar answered Feb 21 '23 01:02

Hunter McMillen


Just use "split" function in JavaScript string,

var url = '/Mobile/Evol/12-20-2011';
var tokens = url.split('/');
var reqURL = token[0] + '/'+ token[1] ;

Of course the URL format must be the same some_string/some_string/some_string

like image 45
RANIL Avatar answered Feb 21 '23 01:02

RANIL