# Getting a substring of a string in JavaScript

I can have one of the following strings:

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


I always want only the myuser part of the string!

I tried the following in JS

var n = username.lastIndexOf('|');


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 \\?

• Why do you have first one username and then a var username? – Simon Forsberg Sep 13 '16 at 12:23
• This is a sample which based on var username. The other usernamex are possible variants which must be also processable. – STORM Sep 13 '16 at 12:25

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.

• Uh... definitely the more simple and elegant one. We all feel stupid now :) – cFreed Sep 13 '16 at 9:53
• @cFreed Honestly, I was doubting myself when I put this down because of all the other answers; I thought for sure I was missing something. – SirPython Sep 14 '16 at 1:10

sounds like you want to do split

var domainAndUsername = username.split('|').pop()

• line2 is the correct answer, and .split("\\").pop() will work for all 3 types of username format given in the OP – Jonah Sep 12 '16 at 20:01

A regex match would be simpler, though it may be overkill.

var strings = [
"i:0#.f|myprovider|domain\\myuser",
"myprovider|domain\\myuser",
"myuser"
];
for (var string of strings) {
console.log(
string, '->',
// here is the only useful line:
string.match(/(?:^|\\)([^\\]*)$/)[1] ); } • The syntax of your regular expression confuses me : /(?:^|\)([^\]*)$/ Is a positive lookahead not " ?= " instead of " ?: " ? – michael.zech Sep 13 '16 at 6:35
• @mizech Not a lookahead, merely a non-capturing flag. Instead I could have chosen match(/(^|\\)([^\\]*\$/)[2]. – cFreed Sep 13 '16 at 9:50
• Haven't known it before. Thanks a lot for your hint. Cool. – michael.zech Sep 13 '16 at 10:45
• Overkill indeed. – Simon Forsberg Sep 13 '16 at 12:20
var n = username.lastIndexOf('|');

• This I totally agree with. There's no reason to use .split or regex, just .substring and .lastIndexOf is enough. – Simon Forsberg Sep 13 '16 at 12:21