Remove Everything After Last Backslash

Remove everything after last backslash

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 stringvar t = "\\some\\route\\here";
// remove everything after the last backslashvar afterWith = t.substr(0, t.lastIndexOf("\\") + 1);
// remove everything after & including the last backslashvar afterWithout = t.substr(0, t.lastIndexOf("\\"));
// show the resultsconsole.log("before : " + t);console.log("after (with \\) : " + afterWith);console.log("after (without \\) : " + afterWithout);

Regular Expression, remove everything after last forward slash

Replace /[^/]*$ with an empty string

Remove everything after last forward slash in Google Sheets with Regex

You may use

=REGEXREPLACE(A1, "(/[^/]+)(?:/\?[^/]*)?$", "$1/")

Details

  • (/[^/]+) - Capturing group 1: / and then 1+ chars other than /
  • (?:/\?[^/]*)? - an optional non-capturing group matching

    • / - a slash
    • \? - a ? char
    • [^/]* - 0 or more chars other than /
  • $ - end of string.

The replacement is $1, the contents of Group 1 and a / that must be present (adding it where it is missing).

How to Remove Everything after the last Slash in a Path Powershell

You can do the following:

(Get-ADUser Identity USER -Properties CanonicalName).CanonicalName -replace '/[^/]*$'

/ matches literal /. [^] is a negated character class making [^/] match anything but /. * is zero or more matches quantifier (greedily matching). $ is the end of string.


Path conversions do work as well, but if your platform's directory separator char is not /, then the / will be converted to something else. Then you will be left with converting them back. It is just more work than using the simple -replace operator.

Replace everything after last forward slash

You need to assign the return value of replaceFirst method to target as no method in String class changes the String object itself:

target = target.replaceFirst("[^/]*$", replace);

JS remove everything after the last occurrence of a character

Here you are: