Remove everything after last backslash

Javascriptnode.jsRegexTypescriptNode Modules

Javascript Problem Overview


var t = "\some\route\here"

I need "\some\route" from it.

Thank you.

Javascript Solutions


Solution 1 - Javascript

You need lastIndexOf and substr...

var t = "\\some\\route\\here";
t = t.substr(0, t.lastIndexOf("\\"));
alert(t);

Also, you need to double up \ chars in strings as they are used for escaping special characters.

Update Since this is regularly proving useful for others, here's a snippet example...

// the original string var t = "\some\route\here";

// remove everything after the last backslash var afterWith = t.substr(0, t.lastIndexOf("\") + 1);

// remove everything after & including the last backslash var afterWithout = t.substr(0, t.lastIndexOf("\"));

// show the results console.log("before : " + t); console.log("after (with \) : " + afterWith); console.log("after (without \) : " + afterWithout);

Solution 2 - Javascript

As stated in @Archer's answer, you need to double up on the backslashes. I suggest using regex replace to get the string you want:

var t = "\\some\\route\\here";
t = t.replace(/\\[^\\]+$/,"");
alert(t);

Solution 3 - Javascript

Using JavaScript you can simply achieve this. Remove everything after last "_" occurance.

var newResult = t.substring(0, t.lastIndexOf("_") );

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionInGeekView Question on Stackoverflow
Solution 1 - JavascriptReinstate Monica CellioView Answer on Stackoverflow
Solution 2 - Javascriptic3b3rgView Answer on Stackoverflow
Solution 3 - JavascriptisuruView Answer on Stackoverflow