2

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 ?

6 Answers 6

3

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 ?

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

1 Comment

substring(0,n+1) to also keep the last "/"
2

Try this...

<!DOCTYPE html>
<html>
<body>

<script>

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

</script>

</body>
</html>

Comments

2

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/

1 Comment

Regex are the most powerfull/generic solution, but they are expensive (for performances). So if you can avoid them, avoid them.
2
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.

Comments

2

Your question is no very much clear. You may try

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

1 Comment

Two too much ";" at the end (1 after parenthetis, 1 before) ;-)
1
var docPath = document.location.pathname.toString();
var sub = docPath.substring(0,docPath.lastIndexOf('/')+1);

This should work

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.