Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS remove everything after the last occurrence of a character

Tags:

javascript

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/"

like image 223
user2238083 Avatar asked Jul 09 '15 04:07

user2238083


3 Answers

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.

like image 80
hungndv Avatar answered Nov 04 '22 07:11

hungndv


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 /).

like image 33
RobG Avatar answered Nov 04 '22 06:11

RobG


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
like image 3
totymedli Avatar answered Nov 04 '22 06:11

totymedli