I'm working on a password reset page where a user types in their username. I'd like to let them know what email it was sent to (sometimes we forget what email we used), without revealing too much information.
So rather than showing: joe_awesome#example.com I'd like to do the following: jo*********#example.com in javascript.
How would I do this efficiently? Basically I'd only like to show the first two letters and the domain only.
P.S. I'm new to javascript. Thanks!
Assuming your email is well formatted and the name has at least 3 characters the solution bellow should work.
var email = "joe_awesome#example.com";
function formatEmail(emilString){
var splitEmail = emilString.split("#")
var domain = splitEmail[1];
var name = splitEmail[0];
return name.substring(0,3).concat("*********#").concat(domain)
}
console.log(formatEmail(email));
In case you want the strings to have the same lengths although i don't recommend it.
function formatEmailSameLength(emilString){
var splitEmail = emilString.split("#")
var domain = splitEmail[1];
var name = splitEmail[0];
return name.substring(0,3).concat(Array(name.length-3).join("*")).concat("#").concat(domain)
}
Just a different answer
const maskEmail = (mail) => {
let mailUsername = mail.split("#")[0];
mailUsername = mailUsername[0] + mailUsername.substring(1).replace(/./gi, '*')
let mailDomain = mail.split("#")[1].split(".")[0].replace(/./gi, '*');
let mailTld = mail.split("#")[1].split(".")[1].replace(/./gi, '*')
return `${mailUsername}#${mailDomain}.${mailTld}`
}
Related
Javascript newbie here, so apologies if this is incredibly basic and not the prettiest coding.
I'm creating a form that I want to have sent to a different email address depending on which team someone selects (e.g. if you select Sales it will generate an email to Team X, Refunds will email Team Y etc).
So far I've got to the stage where I can click a button to generate an email and attach the form as a PDF, but I don't know how to make it variable depending on the field value.
Current code:
var callerName = this.getField("CallerName").value;
var customSubject = this.getField("WhichTeam").value;
//I've used a fake email address for the next line variable, but this is the one I want to change depending on the "WhichTeam" field value
var mailtoUrl = "mailto:Email#email.com?subject=Callback Referral for " + customSubject;
this.submitForm({
cURL: mailtoUrl,cSubmitAs: "PDF"});
Hope this makes sense. Grateful for any help/advice?
Thanks
You can try using an object to contain the emails with the teams as they values. And to also use a template string to insert the value into the mailtoUrl.
var emails = {
refunds: 'refundsTeamEmail',
sales: 'salesTeamEmail',
}
var callerName = this.getField("CallerName").value;
var customSubject = this.getField("WhichTeam").value;
// ex. customSubject value is 'refunds'
// emails[customSubject] would be the same as doing emails.refunds
// which return the value of 'refundsTeamEmail'
var mailtoUrl = `mailto:${emails[customSubject]}?subject=Callback Referral for ` + customSubject;
this.submitForm({
cURL: mailtoUrl,cSubmitAs: "PDF"});
I think this is the simplest way to do it as the value will change each time you run the function to send the email without having to create or call other functions.
Having just said the last thing, you could also use a switch case in another function to return the value. If you want to. Something like:
function fetchEmail(email) {
switch(email) {
case 'refunds':
return 'refundsTeamEmail'
case 'sales':
return 'salesTeamEmail'
default:
return ''
}
}
var callerName = this.getField("CallerName").value;
var customSubject = this.getField("WhichTeam").value;
// ex. customSubject value is 'refunds'
// emails[customSubject] would be the same as doing emails.refunds
// which return the value of 'refundsTeamEmail'
var mailtoUrl = `mailto:${fetchEmail(customSubject)}?subject=Callback Referral for ` + customSubject;
this.submitForm({
cURL: mailtoUrl,cSubmitAs: "PDF"});
here is the regex demo
the REGULAR EXPRESSION
getObj\("Frm_Logintoken"\).value = "(.*)";
this the TEST STRING
getObj("Frm_Logintoken").value = "3";
i want to get that number only "3" without quotes
it's in the Group 1 of the matches but i don't know how to get it from that group .
i can't var myString = "something format_abc";
because i am doing this to get the value that i don't know !!
And testing this in console results
var test = /getObj("Frm_Logintoken").value = "(.*)";/g
undefined
console.log(test1);
undefined
undefined
the same question but in a different way and detailed still unanswered
i have tried
getObj\("Frm_Logintoken"\).value = "(.*)";`.match(/getObj\("Frm_Logintoken"\).value = "(.*)";/)[1]
it give me this "(.*)" not the wanted value !!!
some notes
1-that value isn't static
2- i want to make the code works automatic so fetching the line "getObj("Frm_Logintoken").value = "3";"
from the page code manually is unwanted thing.
3- i want to make an auto login script without any User intervention.
4- if you still don't understand the question see the links pls
thanks
You can access group by accessing index of matched value
let str = `getObj("Frm_Logintoken").value = "3";`
let op = str.match(/getObj\("Frm_Logintoken"\).value = "(.*)";/)
console.log(op[1])
you must declare the string first !
so if you are trying to get the value from the current page html code you can just
let str = document.body.innerHTML;
let pattern =/\bgetObj\("Frm_Logintoken"\)\.value = "([^"]+)";/;
console.log(str.match(pattern)[1]);
and if you are trying to fetch the html string from other page using something like XMLHttpRequest
you can do this
let str = (http.responseText);
the full code :
const http = new XMLHttpRequest();
const url = 'http://page/';
http.open('get', url, false);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function ()
{
if(http.readyState === 4)
{
if(http.status === 200 || http.status == 0)
{
let str = (http.responseText);
let pattern =/\bgetObj\("Frm_Logintoken"\)\.value = "([^"]+)";/;
let results = str.match(pattern)[1];
console.log(results);
}
}
}
http.send();
Hope you understand and make a Clearer question next time and write your really point of the question and the use of the wanted fix .
I have a post that contains a content body, the text in content body need to be properly formatted.
If the content contain a special keyword #, # i want to convert it to a usefull link.
content = "These is a sample post it can contain any thing and i can mention people with #username and show hastag reference #stackoverflowQuestion";
newContent = content.split(" ");
username = [];
hashtag = [];
newContent.forEach((sub) => {
at = sub.indexOf("#");
tag = sub.indexOf("#");
if(at == 0){
trendname.push(sub)
}
if(tag == 0){
hashtag.push(sub)
}
return sub;
});
username.forEach((user) => {
user.link = user.replace(/#/, "/${user}");console.log(user.link);
return user;}); console.log(user.link);
hashtag.forEach((str) => {
str.taged= str.replace(/([a-z])([A-Z])/g, '$1 $2').toLowercase;
return str;}); console.log(str.taged);
Firstly the code above is not loging vakue outside the loop.
Secondly is there any other way to re-write these sode because it look in efficient. if there is Please specify.
Thanks
your question is a little bit complicated to understand I think... But anyways I hope the following will help you somehow.
First, you can simplify your first loop to:
let usernames = content.match(/#([^ ]*)/g)
let hashtags = content.match(/#([^ ]*)/g)
Those are regex, and they work as follow:
They begin with # or # (if you are looking for usernames or hashtags)
[^ ]* means "Everything but a white space, and multiple times (*)
So now, you can construct user objects:
let users = usernames.map(username => {
return {
username: username,
link: '/' + username.slice(1, username.length)
}
}) // --> [ { username: '#username', link: '/username' } ]
Here is the complete code I wrote:
let content = "These is a sample post it can contain any thing and i can mention people with #username and show hastag reference #stackoverflowQuestion";
let usernames = content.match(/#([^ ]*)/g)
let hashtags = content.match(/#([^ ]*)/g)
let users = usernames.map(username => {
return {
username: username,
link: '/' + username.slice(1, username.length)
}
})
console.log(users)
Something is wrong with your code. You are making a forEach on an array of strings, and then you try to set a property to that string: user.link = ....
Secondly, you are trying to log values outside of your loops, and doing so puts you out of the scope of the loop. So you can't log those variables and this is completely normal because they just don't exist anymore... Try to indent your code better, you'll see it directly.
Hope this helps, and try working a little bit on the redaction of your questions, the stack overflow community can be harsh some times
Could you please help to do the following in JavaScript:
The text contains something like that:
text_to_parce = "<b>word</b> <b>192.168.0.1</b> <b>name</b> <b>192.168.1.19</b> <b>address</b>"
From this string I want to extract ONLY IP addresses, other tagged info should be ignored, to the array to get the following:
192.168.0.1
192.168.1.19
var ip_pattern= /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/gi;
var userip_array = text_to_parce.match((/<li>(ip_pattern)<\/li>/)[1]).join("\n");
message.innerText = (userip_array);
It seems to be not working at all. Please help where is the mistake!
This works for two ip as you show.
text_to_parce = "<b>word</b> <b>192.168.0.1</b> <b>name</b> <b>192.168.1.19</b> <b>address</b>";
var numberPattern = /\d+/g;
var a=text_to_parce.match( numberPattern );
var ip_1=a[0]+'.'+a[1]+'.'+a[2]+'.'+a[3];
var ip_2=a[4]+'.'+a[5]+'.'+a[6]+'.'+a[7];
console.log(ip_1);
console.log(ip_2);
I have two fields that I'd like to match. (already done the validation functions for field 1 and 2)
field01 has a client number Txxxxx xxxxx (can be T G or M)
field02 has the area code 416 / 905 / 647
I'd like to match T with 416, G with 905, and M with 647.
and show a relationship error if the rules were broken.
I made a separate function trying to compare the two.
function validatecompare(errMessages)
{
var clientID = document.pizza.field02;
var telenum = document.pizza.field03;
var client = clientID.value;
var phone = telenum.value;
var firstL = "";
var areaC = "";
firstL=client.substr(0,1);
areaC =phone.substr(0,3);
if ((firstL) !=areaC)
{
errMessages += "<li>Client Number and Telephone No. are not consistent with our set up rules.</li>\n";
}
return errMessages;
}
I know that's wrong, I just have no idea how to compare two fields from two separate functions. The error message will pop up regardless of what I do. Even if I violate the rules for field 1 and 2 the error message will pop up with those when it shouldn't.
If there is somewhere I can read up on how to do this would be excellent for future reference.
any help would be greatly appreciated, thanks.
You're literally comparing 416 and T. You need some kind of lookup table:
function validatecompare(errMessages) {
var clientID = document.pizza.field02;
var telenum = document.pizza.field03;
var client = clientID.value;
var phone = telenum.value;
var firstL = client.charAt(0);
var areaC = phone.substr(0, 3);
var areaCodes = {
'416': 'T',
'905': 'G',
'647': 'M'
};
if(firstL !== areaCodes[areaC]) {
errMessages += "<li>Client Number and Telephone No. are not consistent with our set up rules.</li>\n";
}
return errMessages;
}