Js Remove Everything After The Last Occurrence Of A Character
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('/')
Solution 1:
Here you are:
varURL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
alert(URL.substring(0, URL.lastIndexOf("/") + 1));
Hope this helps.
Solution 2:
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 /).
Solution 3:
varURL = "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
Solution 4:
Generic solution
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.
functiontrimStringAfter(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
Solution 5:
Try this jsfiddle or run the code snippet.
varURL = "http://stackoverflow.com/questions/10767815/remove-everything-before-the-last-occurrence-of-a-character";
var myRegexp = /^(.*\/)/g;
var match = myRegexp.exec(URL);
alert(match[1]);
Post a Comment for "Js Remove Everything After The Last Occurrence Of A Character"