I'm fairly new to GAS but learning fast. Thanks in advance for any help you can offer on this!!
I need to be able to send an email to two different email addresses based on the first characters of my last name field. So, if the first character of var last is A - L, send the email to this person, otherwise, if the first character is M - Z, send to this other person. How would I create a conditional if statement for this? My current script which currently sends all email to the same address is as follows:
function onFormSubmit(e) {
var timestamp = e.values[0];
var last = e.values[3];
var first = e.values[4];
var employment_status = e.values[5];
var unemployed_date = e.values[6];
var employment_type = e.values[7];
var employer_name = e.values[8];
var employer_address = e.values[9];
var employment_begin = e.values[10];
var comments = e.values[11];
var email = "xxxxx#gmail.com";
var subject = "Employment Update Received";
var message = "<HTML><BODY>"
+ "<P>Dear " + first + " " + last + ","
etc. etc.
+ "</HTML></BODY>";
MailApp.sendEmail(email, subject, "", {htmlBody: message});
}
#JonnyJS is on the right track. I used just regular expressions. Regex literals are wrapped in / / and options occur after the last /. I usually use RegexPal to test regular expressions for GAS. You can find more information about JS Regex on MDN. Most notably, the test function that I use below.
Here's the regex I used:
^ Starts of string
[A-L] Any letter A-L
.* Any character, 0 or more times
$ End of String
i Option for case insensitive regex
Here is a snippet for you to use.
var last = e.values[3].trim(); // Remove any leading spaces to be safe
var email = "Catch-Other-Names#mydomain.com";
var reAtoL = /^[A-L].*$/i;
var reMtoZ = /^[M-Z].*$/i;
if (reAtoL.test(last)) {
email = "A-to-L-Recipient#mydomain.com";
} else if (reMtoZ.test(last)) {
email = "M-to-Z-Recipient#mydomain.com";
}
// If both fail, then it's going to the Catch Other Names
Mail.sendEmail(email, subject, "", {htmlBody:message});
You havent been really clear but i hope i got what you meant.
I solve it by using two built in js stuff.
we cut the string to the first latter.
we matching the cutted part to regular expression.
Consider view that on JSFIDDLE
lets write the markup first:
<form>
<input name="last" type="text"/></form>
<br><br>
<div id="status">
</div>
now some JS:
var rel = new RegExp("[a-l A-L]");
var rez = new RegExp("[m-z M-Z]");
$("form input").on("change",function(e){
vall = $("form input").val().substr(0,1);
console.log(vall);
if (rel.exec(vall)) {
$("#status").text("We Got a winner! the last name starts with letter from a-l");
}
else if (rez.exec(vall)) {
$("#status").text("Hodey! the last name starts with letter from m-z");
}
else {
$("#status").text("Well, Nothing cool here.");
}
});
as you can see im using jquery to prettify things.
if you still in trouble please write in comments.
Related
What I need is to check for several key words within a textarea before allowing my students to submit their lesson summaries.
The following regex works fine as long as they don't click enter to create a new paragraph.
/^(?=.*\bmodel|models\b)(?=.*\btheory|theories\b)(?=.*\blaw|laws\b)(?=.*\bscale\b)/i;
From what I've been reading, it would seem that the following modification to the regex should allow my validation script to read across line breaks, but I haven't had any success.
var ck_summary = /^(?=.[\S\s]*\bmodel|models\b)(?=.[\S\s]*\btheory|theories\b)(?=.[\S\s]*\blaw|laws\b)(?=.[\S\s]*\bscale\b)/i;
I'm (obviously) a beginner at this and eager to learn. Can anyone please explain what am I doing wrong? Many thanks!
Here's my entire summary validation script...
var ck_studentid = /^[0-9]{6,6}$/;
var ck_summary = /^(?=.[\S\s]*\bmodel|models\b)(?=.[\S\s]*\btheory|theories\b)(?=.[\S\s]*\blaw|laws\b)(?=.[\S\s]*\bscale\b)/i;
function validate(sumform){
var studentid = sumform.studentid.value;
var summary = sumform.summary.value;
var errors = [];
if (!ck_studentid.test(studentid)) {
errors[errors.length] = "Check your Student ID";
}
if (!ck_summary.test(summary)) {
errors[errors.length] = "Make sure you used all of the vocabulary terms AND you spelled them correctly.";
}
if (errors.length > 0) {
reportErrors(errors);
return false;
}
return true;
}
function reportErrors(errors){
var msg = "Uh oh, looks like we have a problem...\n";
for (var i = 0; i<errors.length; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
From what I've been reading, it would seem that the following
modification to the regex should allow my validation script to read
across line breaks, but I haven't had any success.
var ck_summary = /^(?=.[\S\s]*\bmodel|models\b)(?=.[\S\s]*\btheory|theories\b)(?=.[\S\s]*\blaw|laws\b)(?=.[\S\s]*\bscale\b)/i;
This didn't work for you because you did not modify it very well.
.*: captures every character/word except a newline \n, that was why you were told to modify it to [\S\s]* which capture every character/word including a newline \n. But looking at your pattern, you didn't totally modify it, you should remove all the dots . before [\S\s]*.
Your new code should be like this
var ck_summary = /^(?=[\S\s]*\bmodel|models\b)(?=[\S\s]*\btheory|theories\b)(?=[\S\s]*\blaw|laws\b)(?=[\S\s]*\bscale\b)/i;
This question already has answers here:
Split First name and Last name using JavaScript
(26 answers)
Closed 7 years ago.
I am having a hard time chaining some methods together. Can you please provide some assistance?
The end result should = Mickey MOUSE
var name = "MicKEy MOUse";
function nameChanger(oldName) {
var finalName = oldName;
var splitString = name.split(' ');
var fname = splitString.slice(0,1);
var fname_lower = fname.toLowerCase.slice(1,6);
return fname_lower;
};
console.log(nameChanger(name));
Since I am trying to learn the methods in the function I would appreciate assistance on those items. However, if there are more eloquent ways of performing the same action I would appreciate that input as well.
Thank you in advance for your knowledge and direction.
Split the name into two, based on the space character
var splitString = oldName.split(' ');
Convert the entire first string to lowercase and the second string to uppercase.
var fname = splitString[0].toLowerCase();
var lname = splitString[1].toUpperCase();
Now, just create a new String from fname, by changing the first character to upper case, join it with lname and return it, like this
return fname[0].toUpperCase() + fname.substring(1) + " " + lname;
So, your complete function would look like this
function nameChanger(oldName) {
var splitString = oldName.split(' ');
var fname = splitString[0].toLowerCase();
var lname = splitString[1].toUpperCase();
return fname[0].toUpperCase() + fname.substring(1) + " " + lname;
};
Note: You might be wondering, why we are doing this
fname[0].toUpperCase() + fname.substring(1)
to change just the first character of fname. In JavaScript, Strings are immutable objects. Once a String object is created, it can never be changed. So, we are creating a new String object, based on the modified first character of fname and the rest of fname.
var name = "MicKEy MOUse";
function nameChanger(oldName) {
var splitString = name.split(' ');
return splitString[0].charAt(0).toUpperCase()+splitString[0].slice(1).toLowerCase()+' '+splitString[1].toUpperCase();
};
console.log(nameChanger(name));
Expanded code (for Robert Rossmann):
var name = "MicKEy MOUse";
function nameChanger(oldName) {
//Splitting `oldName` to array with words
var splitString = name.split(' ');
//Setting variable which contains first word
var firstWord = splitString[0];
//Setting variable which contains second word
var secondWord = splitString[1];
//Setting variable which contains first letter of first word
var firstWordLetter = firstWord.charAt(0);
//Setting variable which contains first word letters, without first letter
var firstWordRestOfLetters = firstWord.slice(1);
//Result first word (first letter to upper case, rest of letters to lower case)
var resultFirstWord = firstWordLetter.toUpperCase()+firstWordRestOfLetters.toLowerCase();
//Result second word (all second word letters to upper case)
var resultSecondWord = secondWord.toUpperCase();
//Returning string with first and second word separated with space
return resultFirstWord+' '+resultSecondWord;
};
Im doing a javascript bot, that reads the chat whenever someone uses !example #example123
it would add user to an array using the word what's after the "#", since im new to Javascript, i have failed approx. 60 times already, and thought maybe someone here can help me out.
Here's a small example what's in my mind.
ps. The page has an API (API.sendChat("text")).
API.on(API.CHAT, onChat);
function example();
var msg = data.message;
var args = msg.trim().split(" ");
var array = new Array();
var username = data.from
array = [];
Tried:
if (args[0] == "!example" && args[1].indexOf("#") //what's next?) {
}
if (args[0] == "!example" && args[1] == username()) {
add user to array
}
as the manual states indexOf takes a second parameter, instructing the function to search starting from specific position. So when you want to extract the word after the # sign you are lookign for the portion of text between # and the next space eg
hello #valerj how are you
^ ^
p1 p2
so you would use
p1 = str.indexOf('#');
p2 = str.indexOf(' ',p1);
name = str.substr(p1,p2-p1); //substr want start and length
yet as you see it would fail on a lot of strings like
hello #valerij, how are you
ping #valerij
^line end
you could adress this issue by using regex to obtain the p2 eg
p2 = str.indexOf(/ ,.?!$/,p1);
but it might still fail. The best solution would be to use regex for all the operation eg
var myregexp = /#(\w+)\b/;
(the \b is word boundary and will take care of all punctuation, line endings and other characters)
and use this code
var userNames = [];
var match = myregexp.exec(str);
while (match != null) {
//username is in match[1] (first capturing group)
userNames.push(match[1]);
match = myregexp.exec(subject);
}
to populate the array with usernames mentioned in the chat message
I am trying to "clean" a text string that looks something like this:
DATABASE:madsat NL:Show all platforms of Salute generated from NAIs with no go mobility.
The cleaned string should look like this:
Show all platforms of Salute generated from NAIs with no go mobility.
I am trying the following code but it doesn't seem to like it when I pass in a variable as the string gets returned unchanged:
$(document).ready(function(){
$.get('inputQueryExamples.txt',function(data){
var queryString = data;
var cleanString = "";
var db = '';
$('#database-list').change(function(){
db = $('#database-list').val();
// /(^DATABASE:.*\r\n)(^NL.*)/gm
// http://regex101.com/r/mN4hS2
regex = new RegExp('(^DATABASE:'+ db +'\r\n)(^NL.*)' ,'gm');
console.log(db);
console.log(regex);
//put code in here to replace un-needed stuff
$('#what').append(regex + '<br>');
cleanString = queryString.match(regex);
var nlString = cleanString.map(function(el) {return el.replace('DATABASE:' + db + ' NL:','');});
for (i=0; i<nlString.length; i++){
$('#what').append(nlString[i]+'<br>');
}
}); // end change
Any insight into what i am doing wrong will be appreciated. Thanks
So this works, but I am not sure why I have to process the string twice. Can anyone explain?
var nlString = cleanString.map(function(el) {return el.replace('DATABASE:' + db,'');});
nlString = nlString.map(function(el){return el.replace('NL:',''); });
Something like this?
var s = "DATABASE:madsat \r\nNL:Show all platforms of Salute generated from NAIs with no go mobility.";
var db = "madsat";
var r = new RegExp('(^DATABASE:'+ db + '[\\s\\r\\n]*)(^NL:)' ,'gm');
s1.replace(r, "");
//=> "Show all platforms of Salute generated from NAIs with no go mobility."
Update
It took a while for what you're trying to do to sink in (and your sample data was pretty buried in that regex101 link.)
But I think this JSBin is something close to what you want to do: It still does one pass to find the matches, and a second one to remove the unwanted parts of that match. But the second pass is handled by a single regex replace call rather than your double replaces above. (Click the "Run with JS" button and enter "madsat" or "geoquery" in the box.)
This is the relevant code:
$(document).ready(function() {
$.ajax('http://jsbin.com/fase/1.js', {dataType:'text'}).done(function(data){
var $what = $("#what");
$('#database-list').change(function(){
var db = $(this).val(),
base = '(^DATABASE:'+ db + '[\\s\\r\\n]*)(^NL:)';
var regex1 = new RegExp(base + '(.*)' ,'gm');
var regex2 = new RegExp(base, 'gm');
(data.match(regex1) || []).map(function(str) {
return str.replace(regex2, "");
}).forEach(function(query) {
$what.append(query + "<br/>");
});
});
});
});
Note that the two regexes are identical except that the first one matches the remainder of the "NL:"-line, and the second one doesn't.
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.