How to remove an email from a string with JavaScript (GTM) - javascript

This might sound quite simple and since I'm not as experienced as I would like handling javascript, I want to remove an email from a string, actually is an error message while trying to login or sign up.
My errors look like this:
The following email xxxx#gmail.com is incorrect
Invalid Data
Must close the current session
Mail already registered
...
So the idea is to remove the email from the first error, and if there is no email present then leave the other errors as they are now.
I found this code to detect if there is an email in a string but can't find a way to make it work "([^.#\s]+)(\.[^.#\s]+)*#([^.#\s]+\.)+([^.#\s]+)"
I just want to send the data to google analytics, and I'm trying to avoid sending personal data.
Thanks in advance.

"([^.#\s]+)(\.[^.#\s]+)*#([^.#\s]+\.)+([^.#\s]+)" is a regular expression. It matches everything that looks like an email. You can use it with the replace() and search() JavaScript functions, you need to delimit the expression with two /.
Example:
var myString = "Hello, my email is blabla#blabla.com";
// Check if there is an email
if(myString.search(/([^.#\s]+)(\.[^.#\s]+)*#([^.#\s]+\.)+([^.#\s]+)/) !== -1){
console.log("There is an email !");
// Remove it...
myString = myString.replace(/([^.#\s]+)(\.[^.#\s]+)*#([^.#\s]+\.)+([^.#\s]+)/,"");
console.log(myString); // Hello, my email is
}
Good tutorial about JavaScript regular expressions: http://www.w3schools.com/js/js_regexp.asp

Related

Regex for Email ([A-Za-z]{2,4})$/

I was reading this link to understand regex:
https://www3.ntu.edu.sg/home/ehchua/programming/howto/Regexe.html
In my code, Here is what I have:
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
I was testing this email: "test#tatsu.works", and I got error "Please Enter Valid Email ID"
If I understand correct, it is related to the ending section .([A-Za-z]{2,4})$/
I though the {2,4} means 2 to 4 characters, so I changed to {2,6}, but still getting error.
Basically the ".works" can be any number of characters.
Can I know what I do wrong?
Kind Regards
=================================================================
EDIT:
Apparently, changing to {2,6} or {2,} works, but the reason why it is not working for me is because I am using Chrome and somehow the javascipt is not refreshed (I think related to cookie)
When I switched to Edge, the regex works.
Anyway Thanks to user Wiktor Stribiżew
Parsing emails for validity using a regex is a non trivial problem.
These are all valid emails that your regex will fail
'Long live the king'#com
This\ is\ my##email.address
Fred\#barney#bedrock.gov
See https://beesbuzz.biz/code/439-Falsehoods-programmers-believe-about-email and look up the bits about email addresses.
I'd just use filter_var with the FILTER_VALIDATE_EMAIL flag to check, if an email address is in the correct format.
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// valid email address
}

Regular Expression to validate if user has provided the correct URI format or not

I am trying to write a regular expression or regex for my HTML input field with text type. The user should enter the URI in the input field. The URI would look something like this: urn:URNNamespace:**:class:ObjClassid.
Some of the examples of valid URI are as follows:
urn:abc:testing:pqrs:1234556.1244
urn:wxyz:testing123:abc:1234556.*
urn:global:standard:value:myvalue
I was trying to check only if the initial characters are URN using the expression ^(urn):// and check if the string contains the character : in it.
I just want to make sure that user enters valid URN similar to the one that's provided. Is there any better way I can use and achieve this?
I would recommend a really great tool called Regulex that helps you build regular expressions.
I tried to create the described pattern and ended up with:
^urn:\w+:\w+:\w+:\d+(\.\d+)?$
You can try and change it here

Validate email address copied from Outlook

Want to validate email fields where user can enter any kinds of emails .
My validation check using regex fails when user copy pasted email address from Outlook. Email address copied from Outlook looks different as
M, Karan <karan.m#outlook.com>
And my input looks like m.karan#yahoo.com,M, Karan <karan.m#outlook.com>. How to validate this input.
++adding code snippet
Am passing individual emails by splitting it with comma separator to below function,
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
This logic broke when emails copied from outlook available in input element.
Looking forward for help.
1. Solution
Use regular expression like this (but concrete this regex is not the best of the world :) ):
^(([a-zA-Z\-0-9,.: ])*<){0,1}(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))>{0,1}$
2. Solution
Write JavaScript function that parse email and then use your regular expression. Here is example of parse function:
function parseEmail(origin) {
return origin.substring(origin.lastIndexOf('<')+1, origin.lastIndexOf('>'));
}

Parsing string to find email within string via Google Apps Script

I'm not a new coder, but new to google app scripts. I am trying to take a string and find the email address contained within the string.
string = "This is the body of the cell where I will be looking. This body has an email in it somewhere like john.doe#aol.com here.";
email = FindEmail(string);
MailApp.sendEmail(email, "Completion Email", "", "this is the email message");
I need to build a function called FindEmail but frankly have no idea how to start.
While there are numerous solutions to this on SO already, the ones I've found need tweaking to provide the simplicity you're looking for.
How to find out emails and names out of a string in javascript
Regex for email matching
Use javascript to find email address in a string
Get all email addresses in a string with JavaScript
Many more...
Here's a simple function condensed from all those other answers - the regular expression is a bit of overkill, actually, but can also be used to validate in many cases. It returns an array of addresses, so if you only want the first one, you would code email = findEmails(string)[0]... but really, you should do some error checking before trusting that.
/**
* Return an array of all email addresses found in input string.
*/
function FindEmails(input) {
var regex = /(?:[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/gm
var result = input.match(regex);
return result;
}
An email address parsing library "email-addresses" has been adapted for Google Apps Script. Source is forked and available as a gist.
Publicly available, library key M26NvEFUvGLQadhq7G3OQmgFzUAA6_aCl.
Documentation available here.
However... it will not find the email address in the string example you give! It expects the string containing addresses to loosely conform to RFC 5322.

regular expression with if statements

I have this as my regular expression:
var email = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
And this is my if statement:
if($('#email').val() ==""){
$('#emailErrorMsg').text("Please enter a valid email address.");
}
else if(!email.test('#email')) {
$('#emailErrorMsg').text("OK");
}
else($('#emailErrorMsg').text("Please enter a valid email address."));
});
When I type in a valid email address it says "OK". However, if I enter just some text for example it still says "OK" when I want it to say "Please enter a valid email address". Anyone any idea. By the way, I'm still an amatuer at this stuff!
The main problem is that you have a ? at the end of the regex, following parentheses that enclose the entire pattern. This effectively makes the entire match optional, so the regex will literally match anything.
Note also that you are testing the literal string #email, not the value of the #email element. Make sure you pass the appropriate string to test().
I see that you have jquery tag, so take a look to JQuery validate plugin, it will be better than a simple regex.
But if you still want regex, see Validate email address in JavaScript?
Validating emails is hard. The fully correct regex is a true monstrosity that you can see (if you dare) at http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html which probably isn't what you want.
Instead, you have a few options. Use a regex that matches 99% of emails, do it server side with an email validation library, or implement a finite state machine to parse it correctly. The state machine is probably too bulky (although allows neat stuff like suggestions for possible typos) and doing it all server side -- which you better be doing anyway (what if someone has JavaScript disabled?) -- loses the benefits of as-you-type checking.
That leaves a simpler regex that doesn't match all legal emails, but matches enough that the chances of someone registering with one that it doesn't are really slim.
The regex from Validate email address in JavaScript? should do the trick pretty well:
/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\
".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA
-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
Also, you made a small typo:
else if(!email.test('#email')) {
$('#emailErrorMsg').text("OK");
}
is testing against the string '#email' -- not the element with the ID 'email'. Change that to:
else if(!email.test($('#email').val())) {
$('#emailErrorMsg').text("OK");
}
There's a little typo in your regex. Try this:
var email = /^([\w-\.]+)#([\w-]+\.)+[\w-]{2,6}?$/;
That should also handle the .museum case

Categories