Okay I have this
var URL = \"http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character\";
console.log(URL.subst
Try utilizing .match()
with RegExp
/^\w+.*\d+\//
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
var res = URL.match(/^\w+.*\d+\//)[0];
document.body.textContent = res;
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
console.log(URL.substring(0,URL.lastIndexOf('/')+1));
//The +1 is to add the last slash
Try an array based extraction like
var URL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
snippet.log(URL.split('/').slice(0, 5).join('/'));
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<!-- To show result in the dom instead of console, only to be used in the snippet not in production -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
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
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 /).
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.