How to cut a string at the end delimited by a special character when this character is used multiple times within the same string in JavaScript?

Viewed 151

I need to splice the last part of a string until we reach the first / character backwards. Which means if I have the following:

str = "Hello/World/Peace";

I would only like to take:

str = "Hello/World";

Where /Peace is removed.

The string could be longer: a/b/c/d/e/f so the result would always be by removing the last slash with what comes next => a/b/c/d/e.

I've checked this post, but it only works if there is only one slash:

str = "hello/world/wide/peace";
new_str = str.substring(str.indexOf("/")+1);

And the result is by splicing at the beginning not the end of it:

new_str = "world/wide/peace";

The desired output should be:

new_str = "hello/world/wide"

Here is a fiddle.

2 Answers
str.slice(0, str.lastIndexOf("/"))

Given that str is hello/world/wide/peace, str.lastIndexOf("/") will find the last occurence of / in str. And then you slice the string from the beginning up to that index, and you take all that and you get hello/world/wide

var str = "hello/world/wide/peace";
console.log(str.slice(0, str.lastIndexOf("/")));

The snippet logs hello/world/wide to the console.

How about something like this?

const removeLastSegment = (input, separator = '/') => {
  const segments = input.split(separator);
 
  segments.pop();
  
  return segments.join(separator);
}

var str = "hello/world/wide/peace";


console.log(removeLastSegment(str));

Related