Quantcast
Channel: User totymedli - Stack Overflow
Viewing all articles
Browse latest Browse all 54

Answer by totymedli for JS remove everything after the last occurrence of a character

$
0
0

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.

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

Viewing all articles
Browse latest Browse all 54

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>