Getting a substring of a string in JavaScript I can have one of the following strings:

var username = "i:0#.f|myprovider|domain\\myuser"
var username2 = "myprovider|domain\\myuser"
var username3 = "myuser"


I always want only the myuser part of the string!

I tried the following in JS

var n = username.lastIndexOf('|');
var domainandusername = username.substring(n + 1);
var m = domainandusername.lastIndexOf('"\\"');
var username = domainandusername.substring(m + 1);


I have tried it within a simple page with JS and it seems to work. But is this a good way to solve this? I mean is it a good practice even to do this for string username2 and username3 where I know that they, for example, do not have a | and \\?
You don't need to over-complicate things. The myuser part will always come at the end of the string, after \\ if it's there.

All you need is this:

username.split("\\").pop();


Even if the username is entered like the third version, the myuser will be returned.