zey
zey

Reputation: 6103

how to substring in javascript

My javascript code ,

var docPath = document.location.pathname.toString()

returns

/myFolder/UserControls/myUserControl.ascx

I want to subString likes

/myFolder/UserControls/

How can I do it ?

Upvotes: 2

Views: 293

Answers (6)

Atish Kumar Dipongkor
Atish Kumar Dipongkor

Reputation: 10422

Your question is no very much clear. You may try

var docPath = document.location.pathname.toString()
.substring(0,document.location.pathname.toString().lastIndexOf("/")+1);

Upvotes: 2

Gangadhar
Gangadhar

Reputation: 1749

var docPath = document.location.pathname.toString();
var sub = docPath.substring(0,docPath.lastIndexOf('/')+1);

This should work

Upvotes: 1

JREN
JREN

Reputation: 3630

var x = docPath.lastIndexOf("/");
var substr = docPath.substr(0, (x+1));

This will look for the last "/" character in your string and return it's position. Then it will take your string and put the characters from 0 to your last "/" character and put it into the substr var.

Upvotes: 2

Erik Schierboom
Erik Schierboom

Reputation: 16656

You can use the match string method:

var fullPath = '/myFolder/UserControls/myUserControl.ascx';
var path = fullPath.match(/(.+\/)/);
alert(path[1]); // This will output "/myFolder/UserControls/"

You can verify the working at the following JSFiddle: http://jsfiddle.net/H5PGb/

Upvotes: 2

Ganesh Rengarajan
Ganesh Rengarajan

Reputation: 2006

Try this...

<!DOCTYPE html>
<html>
<body>

<script>

var str=document.location.pathname.toString();
document.write(str.substring(0,str.lastIndexOf("/")));;

</script>

</body>
</html>

Upvotes: 2

Ricola3D
Ricola3D

Reputation: 2442

Mhh..

var n=str.lastIndexOf("/"); // get the last "/"
var result = str.substring(0, n); // only keep everything before the last "/" (excluded)

Does what you want ?

Upvotes: 3

Related Questions