Okay I have this
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
console.log(URL.substring(URL.lastIndexOf("/")));
Gives you "/remove-everything-before-the-last-occurrence-of-a-character"
How do I get "http://stackoverflow.com/questions/10767815/
"
Here you are:
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
alert(URL.substring(0, URL.lastIndexOf("/") + 1));
Hope this helps.
Seems like a good case for a regular expression (can't believe no one has posted it yet):
URL.replace(/[^\/]+$/,'')
Removes all sequential non–forward slash characters to the end of the string (i.e. everything after the last /).
This is a generic function that also handles the edge case when the searched character or string (needle) is not found in the string we are searching in (haystack). It returns the original string in that case.
function trimStringAfter(haystack, needle) {
const lastIndex = haystack.lastIndexOf(needle)
return haystack.substring(0, lastIndex === -1 ? haystack.length : lastIndex + 1)
}
console.log(trimStringAfter('abcd/abcd/efg/ggfbf', '/')) // abcd/abcd/efg/
console.log(trimStringAfter('abcd/abcd/abcd', '/')) // abcd/abcd/
console.log(trimStringAfter('abcd/abcd/', '/')) // abcd/abcd/
console.log(trimStringAfter('abcd/abcd', '/')) // abcd/
console.log(trimStringAfter('abcd', '/')) // abcd
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With