I am trying to add a check to see if an email (string) is part of a specific domain in google scripts. For example, the domain would be "#company.com", so all emails with this would pass the check and emails without it won't
basically what I have is a way to retrieve the current user's email using:
var email = Session.getEffectiveUser().getEmail();
Now I want to check this email for a specific domain/company
Example: abc#companyname.com
so in this case it would be the "#companyname.com" part
I know there usually is a way to do this in other languages but how can I do this in apps script?
Here's a function which uses a regular expression to match valid e-mails, and logs the result. Note that I'm using the i flag to do a case-insensitive search:
function emailCheck(email) {
var regExp = new RegExp("[a-z0-9\.-_]*#companyname\.com$", "i");
match = email.match(regExp);
if(match)
match = true;
else
match = false
Logger.log(email + ' - ' + match);
return match
}
The following inputs:
tests = ['ABC.345#companyNAME.com','no_no#goggle.com','ABC.345#companyNAME.com.edu']
for each (test in tests) {
emailCheck(test);
}
Output:
ABC.345#companyNAME.com - true
no_no#goggle.com - false
ABC.345#companyNAME.com.edu - false
You can test an email by using this simple regular expression:
/#company\.com$/
And with JavaScript you can use this true/false test:
/#company\.com$/.test(email)
Here is a working example:
const emailTest = email => /#company\.com$/.test(email);
['abc#company.com', 'abc#gmail.com', 'abc.123#gmail.company.com', 'defg#company.com', 'abc.123#company.gmail.com']
.forEach(email => console.log(email.padEnd(30), emailTest(email)))
Related
How can I match only numerical email addresses?
I'm testing against the following email addresses:
12345839223#gmail.com <-- want this
38482934934#gmail.com <-- want this
abcaasd#gmail.com <-- don't want this
asdasd123#gmail.com <-- don't want this
123asdasd#gmail.com <-- don't want this
I tried the following regex, but it matches some addresses with letters.
([0-9])+(#+)
The regex /^\d+(?=#)/ will achieve this for you. As you can see from the image below, it looks for the start of the line followed by one or more digits followed by an "#" symbol.
Here's a RegEx101 test case for reference
var emails = [
'12345839223#gmail.com',
'38482934934#gmail.com',
'abcaasd#gmail.com',
'asdasd123#gmail.com',
'123asdasd#gmail.com'
];
function emailNum(email) {
return (/^\d+(?=#)/.exec(email)||[false])[0];
// return the match if it exists or false
}
for(var i in emails) document.write(emails[i]+': '+emailNum(emails[i])+'<br>');
In Javascript, you could have a function like this:
function isNumberEmail(email) {
return /^\d+#.*\./.test(email)
}
emailsToTest = ["12345839223#gmail.com",
"38482934934#gmail.com",
"abcaasd#gmail.com",
"asdasd123#gmail.com",
"123asdasd#gmail.com"]
emailsToTest.forEach(function(email) {
document.write(email + " - " + isNumberEmail(email))
document.write("<br>")
})
You can use the following to test if the first part of the email is a number:
function test( val ) {
var first = val.match(/^([^#]+)/g)[0];
return /^\d+$/g.test(first);
}
console.log(test('12345#email.com'));
console.log(test('12345678#email.com'));
console.log(test('abc12345#email.com'));
console.log(test('12345abc#email.com'));
I think this will work, wouldn't mind if someone can verify. Adds # to capture group
/([1-9][0-9]*)+(#)/g
Edit: ^\d+# works as per #dustmouse's comment
Please see the Javascript code below. The else if block which is doing a check for email pattern is not allowing any of the email ids . What does the match() function return? Please help.
Used test()
empty field :working fine
wron mail id : working fine
Correct email id : not working
var pattern = new RegExp("/^(([^<>()[\]\\.,;:\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,}))$/");
if(!accountantEmail){
$("#infoTextMsg").hide();
$("#accountantEmailNoDataErr").show();
$("#accountantEmailInvalidFormat").hide();
$("#accountant_email").focus();
return false;
}
else if(!(pattern.test(accountantEmail))){
$("#accountantEmailInvalidFormat").show();
$("#infoTextMsg").hide();
$("#accountantEmailNoDataErr").hide();
$("#accountant_email").focus();
return false;
}
Javascript match returns an array containing the matches.
Here's the regular expression I use:
var pattern = "[-0-9a-zA-Z.+_]+#[-0-9a-zA-Z.+_]+\.[a-zA-Z]{2,4}";
if(!(accountantEmail.match(pattern))) {
return false;
}
For validation scenarios, you should use the RegExp#test function.
var pattern = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (!pattern.test(accountantEmail)) {
$("#accountantEmailInvalidFormat").show();
$("#infoTextMsg").hide();
$("#accountantEmailNoDataErr").hide();
$("#accountant_email").focus();
return false;
}
As commented on the other posts, the match function is intended for group capturing.
Also note that you were specifying your pattern with an / on it's beginning. This isn't necessary if you're specifying a RegExp as a string.
I have a regex to match email addresses in javascript. Lets see an example:
var email = "aaa#bbb.com (A,B); ccc#ddd.com (C,D); eee#fff.com (E,F);";
var emails = email.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
This will return me all the emails in the var emails.
Now, I have a string:
var initials = "(A,B)";
And I would like to get only the email before the initials value;
If the var initials is "(A,B)", then I would like to get only the aaa#bbb.com email address.
Thank you a lot for your help!
JavaScript:
var input = "aaa#bbb.com (A,B); ccc#ddd.com (C,D); eee#fff.com (E,F);";
var initials = "(A,B)";
var email = input.match(new RegExp("([a-zA-Z0-9]+(?:[-._][a-zA-Z0-9]+)*#[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*)(?=\\s*" + initials.replace(/([()])/g, "\\$1") + ")"))[0];
print(email);
Output:
aaa#bbb.com
Test this code here.
Whether you have something like this "example#mail.com(A,B)" or like this "(A,B)example#mail.com", all you have to do is have the first and last part of the only capture letters. So the (A,B) should be automatically excluded for he capture of the regex.
If that is not the issue you can always grab the text returned by the regular expression and use replace to change the (A,B) to nothing, just like this:
var regexresult=str.replace("(A,B)","");
That code will remove the string if it's present, otherwise it will do nothing.
I'm trying to do a URL GET variable replace, however the regular expression for checking whether the variable exists in amongst other GET variables is returning true when I am expecting it to return false.
The pattern I am using is: &sort=.*&
Test URL: http://localhost/search?location=any&sort=asc
Am I right to believe that this pattern should be returning false on the basis that their is no ampersand character following the sort parameter's value?
Full code:
var sort = getOptionValue($(this).attr('id'));
var url = document.URL;
if(url.indexOf('?') == -1) {
url = url+'?sort='+sort;
} else {
if(url.search('/&sort=.*&/i')) {
url.replace('/&sort=.*&/i','&sort='+sort+'&');
}
else if(url.search('/&sort=.*/i')) {
url.replace('/&sort=.*/i','&sort='+sort);
}
}
Am I right to believe that this pattern should be returning false on the basis that their is no ampersand character following the sort parameter's value?
Well, you are using String.search, which, according to the linked documentation:
If successful, search returns the index of the regular expression inside the string. Otherwise, it returns -1.
So it will return -1, or 0 or greater when there is a match. So you should test for -1, not truthiness.
Also, there is no need to pass the regexes as strings, you might as well use:
url.replace(/&sort=.*&/i,'&sort='+sort+'&');
Further, keep in mind that replace will create a new string, not replace in the string (strings in Javascript are immutable).
Finally, I don't see the need for searching for the string, and then replacing it -- it seems that you always want to replace &sort=SOMETHING with &sort=SOMETHING_ELSE, so just do that:
if(url.indexOf('?') == -1) {
url = url+'?sort='+sort;
} else {
url = url.replace(/&sort=[^&]*/i, '&sort=' + sort);
}
The javascript string function search() returns -1 if not found, not false. Your code should read:
if(url.search('/&sort=.*&/i') != -1) {
url.replace('/&sort=.*&/i','&sort='+sort+'&');
}
else if(url.search('/&sort=.*/i') != -1) {
url.replace('/&sort=.*/i','&sort='+sort);
}
You should check
if(url.search('/&sort=.*&/i') >= 0)
then it should work
You could use this code
var url = 'http://localhost/search?location=any&sort=asc';
var vars = {};
var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
console.log(vars);
//vars is an object with two properties: location and sort
This can be done by using
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + sort);
The match broken down
Group 1 matches for ? or &
Group 2 matches sort=
Group 3 matches anything that is not a & or ?
Then "$1$2" + sort will replace all 3 group matches with the first 2 + your variable
examples using string "REPLACE" instead of your sort variable
url = "http://localhost/search?location=any&sort=asc&a=z"
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + "REPLACE");
// => "http://localhost/search?location=any&sort=REPLACE&a=z"
url = "http://localhost/search?location=any&sort=asc"
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + "REPLACE");
// => "http://localhost/search?location=any&sort=REPLACE"
url = "http://localhost/search?sort=asc"
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + "REPLACE");
// => "http://localhost/search?sort=REPLACE"
url = "http://localhost/search?sort=asc&z=y"
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + "REPLACE");
// => "http://localhost/search?sort=REPLACE&z=y"
The pattern I am using is: &sort=.*& Test URL:
http://localhost/search?location=any&sort=asc
Am I right to believe that this pattern should be returning false on
the basis that their is no ampersand character following the sort
parameter's value?
you are assuming right. But in your code you have else if(url.search('/&sort=.*/i')) which will match and thus still replace the value.
You should also note that your code would turn http://localhost/search?sort=asc&location=any&some=more into http://localhost/search?sort=asc&some=more. that's because because .* is greedy (trying to match as much as possible). You can avoid that by telling it to match as little as possible by appending a ? like so .*?.
That said, I believe you may be better off with a library that knows how URLs actually work. You're not compensating for parameter position, possible escaped values etc. I suggest you have a look at URI.js and replace your wicked regex with
var uri = URI(document.URL),
data = uri.query(true);
data.foo = 'bazbaz';
uri.query(data);
Why doesn't the following jQuery code work?
$(function() {
var regex = /\?fb=[0-9]+/g;
var input = window.location.href;
var scrape = input.match(regex); // returns ?fb=4
var numeral = /\?fb=/g;
scrape.replace(numeral,'');
alert(scrape); // Should alert the number?
});
Basically I have a link like this:
http://foo.com/?fb=4
How do I first locate the ?fb=4 and then retrieve the number only?
Consider using the following code instead:
$(function() {
var matches = window.location.href.match(/\?fb=([0-9]+)/i);
if (matches) {
var number = matches[1];
alert(number); // will alert 4!
}
});
Test an example of it here: http://jsfiddle.net/GLAXS/
The regular expression is only slightly modified from what you provided. The global flag was removed, as you're not going to have multiple fb='s to match (otherwise your URL will be invalid!). The case insensitive flag flag was added to match FB= as well as fb=.
The number is wrapped in curly brackets to denote a capturing group which is the magic which allows us to use match.
If match matches the regular expression we specify, it'll return the matched string in the first array element. The remaining elements contain the value of each capturing group we define.
In our running example, the string "?fb=4" is matched and so is the first value of the returned array. The only capturing group we have defined is the number matcher; which is why 4 is contained in the second element.
If you all you need is to grab the value of fb, just use capturing parenthesis:
var regex = /\?fb=([0-9]+)/g;
var input = window.location.href;
var tokens = regex.exec(input);
if (tokens) { // there's a match
alert(tokens[1]); // grab first captured token
}
So, you want to feed a querystring and then get its value based on parameters?
I had had half a mind to offer Get query string values in JavaScript.
But then I saw a small kid abusing a much respectful Stack Overflow answer.
// Revised, cooler.
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(window.location.search);
return match ?
decodeURIComponent(match[1].replace(/\+/g, ' '))
: null;
}
And while you are at it, just call the function like this.
getParameterByName("fb")
How about using the following function to read the query string parameter in JavaScript:
function getQuerystring(key, default_) {
if (default_==null)
default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
and then:
alert(getQuerystring('fb'));
If you are new to Regex, why not try Program that illustrates the ins and outs of Regular Expressions