String method, select from email only username - javascript

it is possible to grab from email only data until #gmail.com ?
for example:
myemail#gmail.com
I want to select only
myemail
It should be aplycable for any emails. Any length of emails.
if I have emails:
myemail11#gmail.com and myem#gmail.com
it should give me:
myemail11 and myem
I thing req expreson will be good for that , but I am not goog in reg expr.

The simplest way is by getting string before last # by using substring:
const address = "myemail#gmail.com";
const username = address.substring(0, address.lastIndexOf("#"));
console.log(username)

Apart from the substring, you can also split the email and take the first index value.
const email = "myemail#gmail.com";
const name = email.split('#')[0]
console.log(name)

Related

How to replace elements of a string based on the values of an array?

String has already been defined as follows:
const desc = `This is the password you use to access the $0 application. It is not the password for the $1 card. \n With the password, we can only read your statement. No other operations can be performed.`;
Array has already been defined as follows:
const params = ['American', 'American Black'];
I would like to replace:
$0 => American,
$1 => American Black
Expected outcome:
This is the password you use to access the American application. It is not the password for the American Black card. \n With the password, we can only read your statement. No other operations can be performed.
If you want to make it work for N parameters, you can do:
const desc = `This is the password you use to access the $0 application. It is not the password for the $1 card. \n With the password, we can only read your statement. No other operations can be performed. Added $2 value, Added $3 value`;
const params = ['American', 'American Black', 'test1', 'test2'];
const result = params.reduce((acum, val, index) => acum.replace("$"+index, val), desc);
console.log(result);
Try this:
const params = ['American', 'American Black'];
const desc = `This is the password you use to access the ${params[0]} application. It is not the password for the ${params[1]} card.\nWith the password, we can only read your statement. No other operations can be performed.`;
console.log(desc)
Always be extra cautious when dealing with credit cards and money. Storing such data as a variable on the user-side code is quite dangerous, as it can be read by anyone quite easily.
If you can't edit the string desc then you can replace $0 and $1 as follows:
x = desc.split('$0').join(params[0])
x = x.split('$1').join(params[1])
return x
if you don't want to change the two constants you could simply replace it with:
var newDesc = desc.replace("$0", params[0]).replace("$1", params[1]);

Regular expression for extracting domain from an input

I'm trying to extract the domain.com from an input that can be in the following formats and structure:
1. x.x.domain.com
2. x.domain.com
Once I am getting user's email, for example:
user#x.x.domain.com
I am able to remove the first part of the email address:
user#
by the following regex:
/^.+#/
I want to be able by using the regex over the 2 formats to get the domain.com right away and not manipulate the input several times until getting the domain.
I thought maybe to count the number of dots from the input and then to do some logic, but it looks so complex for this small solution.
Thanks!
Without RegExp: split the e-mail address twice, slice from the last split and join the result. Plus two RegExp ideas. Take your pick.
const getDomain = address =>
address.split("#")[1].split(".").slice(-2).join(".");
const getDomainRE = address =>
address.match(/\.\w+/g).slice(-2).join("").slice(1);
const getDomainRE2 = address =>
address.match(/(?:(#|\.)\w+){2}$/)[0].slice(1);
console.log(getDomain("user#x.x.domain.com"));
console.log(getDomain("user#x.domain.com"));
console.log(getDomain("user#abc.x.y.z.domain.com"));
console.log(getDomainRE("user#x.x.domain.com"));
console.log(getDomainRE("user#x.domain.com"));
console.log(getDomainRE("user#abc.x.y.z.domain.com"));
console.log(getDomainRE2("user#x.x.domain.com"));
console.log(getDomainRE2("user#x.domain.com"));
console.log(getDomainRE2("user#abc.x.y.z.domain.com"));
Regex way:
let str1 = "x.domain.com";
let str2 = "x.sdfsdf.google.com";
let str3 = "www.subdomain.yahoo.com";
let reg = /[^.]+\.[^.]+$/gi;
console.log(str1.match(reg)); // domain.com
console.log(str2.match(reg)); // google.com
console.log(str3.match(reg)); //yahoo.com
Simple javascript:
function getDomain(str){
let arr = str.split(".");
if(arr.length < 2){
console.log("Invalid domain name");
return null;
}
else{
return `${arr[arr.length-2]}.${arr[arr.length-1]}`;
}
}
let str1 = "x.domain.com";
let str2 = "x.sdfsdf.google.com";
let str3 = "www.subdomain.yahoo.com";
console.log(getDomain(str1)); // domain.com
console.log(getDomain(str2)); // google.com
console.log(getDomain(str3)); //yahoo.com
This is regular expression for domain name
"[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$"
should also manage x.x.domain.co.uk
original pattern uses
"(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]"
Good luck
I know you didn't specifically ask for it, but you may want to consider country codes a top level domains as well (e.g. .au, .uk).
If required, you could achieve it with the following:
function getDomainFromEmail(domain) {
const domainExpression = /((\w+)?(\.\w+)(\.(ad|ae|af|ag|ai|al|am|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bl|bm|bn|bo|bq|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cw|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mf|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|ss|st|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|za|zm|zw))?)$/i;
const match = domainExpression.exec(domain);
return match ? match[1] : null;
}
console.log(getDomainFromEmail('email#example.com'));
console.log(getDomainFromEmail('email#sub.example.com'));
console.log(getDomainFromEmail('email#sub.sub.example.com'));
console.log(getDomainFromEmail('email#example.com.au'));
console.log(getDomainFromEmail('email#example.co.uk'));
console.log(getDomainFromEmail('email#sub.example.co.uk'));
console.log(getDomainFromEmail('email#sub.sub.example.co.uk'));
console.log(getDomainFromEmail('email#bit.ly'));
console.log(getDomainFromEmail('email#domain.other'));
console.log(getDomainFromEmail('email#nomatch'));
The long expression (ad|ae|...|zm|zw) is a list of country codes combined into a regular expression.
How about
(#).*
The first group of the output is # and the second group is domain.com

JavaScript email validation - String variable before the #

I need to validate an email address input in JavaScript. The format should be name#xx.xx where "name" is another input text in the form and I have it in a var called "name_input".
I don't know how to be sure that the email will contains that variable before the # sign.
You don't need regex for this. Just String#indexOf will be suffice:
var email = 'name#xx.xx';
var name_input = 'name';
var isValid = (email.indexOf(name_input + '#') == 0);
//=> true

Replace all in JavaScript Regex

i have below string from which I have to extract username and ID.
This is a string which has a #[User Full Name](contact:1) data inside.
To get username and contact id from above string I am using this regex pattern.
var re = /\#\[(.*)\]\(contact\:(\d+)\)/;
text = text.replace(re,"username:$1 with ID: $2");
// result == username: User Full Name with ID: 1
It works perfectly now issue is I have multiple usernames in string, I tried using /g (global) but its not replacing properly:
Example string:
This is a string which has a #[User Full Name](contact:1) data inside. and it can also contain many other users data like #[Second Username](contact:2) and #[Third username](contact:3) and so many others....
when used global I get this result:
var re = /\#\[(.*)\]\(contact\:(\d+)\)/g;
text = text.replace(re,"username:$1 with ID: $2");
//RESULT from above
This is a string which has a user username; User Full Name](contact:1) data inside. and it can also contain many other users data like #[[Second Username](contact:2) and #[Third username and ID: 52 and so many others....
You just need a non greedy ? match in your first capture group. By having .* you are matching the most amount possible while if you use .*?, it matches the least amount possible.
/#\[(.*?)\]\(contact:(\d+)\)/
And if the word contact is not always there, you could do..
/#\[(.*?)\]\([^:]+:(\d+)\)/
See working demo
Can't say I can see how your resulting string is going to be usable. How about something like this...
var re = /#\[(.*?)\]\(contact:(\d+)\)/g;
var users = [];
var match = re.exec(text);
while (match !== null) {
users.push({
username: match[1],
id: match[2]
});
match = re.exec(text);
}

Node.js: Regular Expression to read email from string

How can I take an e-mail address from "XXX <email#email.com>" ? I don't want to get the "< >".
Thanks!
Here's one based on Tejs' answer. Simple to understand and I think a bit more elegant
// Split on < or >
var parts = "XXX <email#email.com>".split(/[<>]/);
var name = parts[0], email = parts[1];
Really simply (no need for regex!)
var components = emailAddress.split('<')
if(components.length > 1)
{
var emailAddress = components[1].replace('>', '');
}
function getEmailsFromString(input) {
var ret = [];
var email = /\"([^\"]+)\"\s+\<([^\>]+)\>/g;
var match;
while ( match = email.exec(input) ) {
ret.push({'name': match[1], 'email': match[2]});
}
return ret;
}
var str = '"Name one" <foo#domain.com>, ..., "And so on" <andsoon#gmx.net>';
var emails = getEmailsFromString(str);
credit: How to find out emails and names out of a string in javascript
^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*#[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$
Matches e-mail addresses, including some of the newer top-level-domain extensions, such as info, museum, name, etc. Also allows for emails tied directly to IP addresses.
This regex will work for your example.
/<([^>]+)/
It searches for anything after the '<' that is not a '>' and that is returned in your matches.
To just grab what's inside the angle brackets, you can use the following:
var pattern = /<(.*)>/;
pattern.exec("XXX <foo#bar.com>"); // this returns ["<foo#bar.com>", "foo#bar.com"]
Not positive if I'm understanding you correctly. If you want to get the email domain ie gmail.com or hotmail.com then you could just use
var x =string.indexOf("#"); var y =string.subString(x)
this will give you the string y as the email domain.

Categories

Resources