Reputation: 93
Hoping you guys can help me out.
I have a dynamic url and I need some javascript to basically trim the string after the specific occurrence of a character.
EXAMPLE:
I have this url
Assessment/testdir2/TestDIR3/lecture slides 1as.pdf
and I need to remove everything after the 2nd slash
and including the 2nd slash.
How would I do this?
Upvotes: 1
Views: 2013
Reputation: 5000
A very basic JS solution:
function removeAfterSlash(word, numberOfElements) {
var splitWord = word.split('/');
var newWord = '';
for(var i = 0; i < numberOfElements; i++) {
if(i != (numberOfElements - 1)) {
newWord += splitWord[i] + '/';
} else {
newWord += splitWord[i];
}
}
document.write(newWord);
}
removeAfterSlash('Assessment/testdir2/TestDIR3/lecture slides 1as.pdf', 1);
Simply split's the word into an array by looking for a /
and then you can join the elements you need back together. The function takes the word and how many 'segments' you want to join back together.
See it on jsfiddle.
Upvotes: 4
Reputation: 337714
Try this:
var url= "Assessment/testdir2/TestDIR3/lecture slides 1as.pdf"
var locs = myString.split('/');
var newUrl = "";
for (var i = 2; i < locs.length; i ++) {
newUrl += "/" + locs[i];
}
This method will then ignore the first two folders and will work regardless of how many other folders you have in the url.
Upvotes: 2