Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove everything after last backslash

var t = "\some\route\here"

I need "\some\route" from it.

Thank you.

like image 916
InGeek Avatar asked Jan 22 '13 15:01

InGeek


People also ask

How do you delete after last occurrence of a character?

The indexOf method returns the index of the first occurrence of a character in the string. If you need to remove everything after the last occurrence of a specific character, use the lastIndexOf method.

How do I delete everything after a character in Notepad ++?

If you want to delete all the text after a character or string (to the right) in Notepad++ you would need to make use of regex. So, simply add . * to delete all characters after the string or character on each that you want to delete from a line.


2 Answers

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);
like image 166
Reinstate Monica Cellio Avatar answered Sep 20 '22 23:09

Reinstate Monica Cellio


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); 
like image 37
ic3b3rg Avatar answered Sep 23 '22 23:09

ic3b3rg