Reputation: 491
var login_id = '[email protected]';
console.log(login_id.substring(0, login_id.lastIndexOf("@")));
Above script works perfectly if I pass input with '@abc.com'
. Does not work if string do not have '@domain.com'
We have some user name with [email protected]
and few are just username. I want extract @domain.com
from user name. Expected output is if input is [email protected]
return output = username
and if input is username, output should be username.
Please help if there is any way.
Upvotes: 0
Views: 315
Reputation: 1296
login_id.includes('@') ? console.log(login_id.substring(0,
login_id.lastIndexOf("@"))) : console.log(login_id) ;
Running example
function username(login_id) {
return login_id.includes('@') ? login_id.substring(0,login_id.lastIndexOf("@")) : login_id ;
}
console.log(username("[email protected]")) ;
console.log(username("sa-testaccount0125")) ;
Upvotes: 0
Reputation: 847
Use .split() method to split your string in parts
It will still work if you do not have @domain.com
const login_id = '[email protected]';
console.log(login_id.split("@")[0])
Output
"sa-testaccount0125"
const login_id = 'sa-testaccount0125';
console.log(login_id.split("@")[0])
Output
"sa-testaccount0125"
Upvotes: 2
Reputation: 11740
If you split on @
then you get an array of items. The first item of the array will be the username, whether there was a @
in it or not.
const test = str => str.split('@')[0]
console.log(test('[email protected]'));
console.log(test('sa-testaccount0125'));
Upvotes: 1
Reputation: 2800
You're already using a indexOf
. Usee that to check @
if exists as well:
function check(login_id) {
if (login_id.indexOf('@') >= 0) {
return login_id.substring(0, login_id.lastIndexOf("@"));
}
return login_id;
}
console.log(check('[email protected]'));
console.log(check('sa-asd'));
console.log(check('[email protected]'));
Upvotes: 0