Need function to take string and remove anything after last "/"

I need function to take string and remove anything after last "/" (backslash). There may or may not be something after it??
894359Asked:
Who is Participating?
 
ldbkuttyCommented:
Slightly better (works even if the testStr does not have the slash):

<script>
testStr = 'This is my / test';
if(testStr.indexOf('/') != -1)  testStr = testStr.substr(0, testStr.lastIndexOf('/'));
alert(testStr);
</script>
0
 
BatalfCommented:
I assume you mean a normal slash "/" and not backslash !?

This is one example of how that could be done:

<script>
var string = 'This is just a simple test/ with some slashes/ after each other / this text should be stripped away';
var stringArray = string.split('/');    // Create array
stringArray.pop();  // remove last item from array
var tmpString = stringArray.join('/');  // Convert array into string
string = tmpString;
document.write(string);  // Output the string withoug the part after the last slash.

</script>

kind regards
Batalf
0
 
ldbkuttyCommented:
<script>
testStr = 'This is my / test / string';
newStr = testStr.substr(0, testStr.lastIndexOf('/'));
alert(newStr);
</script>
0
 
BatalfCommented:
ldbkutty,

Yes of course. I didn't think of the lastIndexOf() function:-) Well done!

Batalf
0
 
ldbkuttyCommented:
Thanks Batalf :=)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.