passing a variable to map & replace - javascript

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.

Related

Trim a variable's value until it reaches to a certain character

so my idea is like this..
var songList = ["1. somesong.mid","13. abcdef.mid","153. acde.mid"];
var newString = myString.substr(4); // i want this to dynamically trim the numbers till it has reached the .
// but i wanted the 1. 13. 153. and so on removed.
// i have more value's in my array with different 'numbers' in the beginning
so im having trouble with this can anyone help me find a more simple solution which dynamically chop's down the first character's till the '.' ?
You can do something like
var songList = ["1. somesong.mid","13. abcdef.mid","153. acde.mid"];
songList.forEach(function(value, i){
songList[i] = value.replace(/\d+\./, ''); //value.substr(value.indexOf('.') + 1)
});
Demo: Fiddle
You can use the string .match() method to extract the part up to and including the first . as follows:
var newString = myString.match(/[^.]*./)[0];
That assumes that there will be a match. If you need to allow for no match occurring then perhaps:
var newString = (myString.match(/[^.]*./) || [myString])[0];
If you're saying you want to remove the numbers and keep the rest of the string, then a simple .replace() will do it:
var newString = myString.replace(/^[^.]*. */, "");

google apps script conditional if statement

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.

Select first complete string matching partial string

I have a page which contains many tags with a string in them, for example 'Am I a String? Yes'.
Using JQuery, I want to get the first instance of 'Am I a String? ' and then take the Yes or No after that and store it so I can use it in a conditional.
Any ideas?
Thanks.
The code I'm going with:
function experimentThree() {
var stringBool = $('*:contains("Was it enough? ")');
console.log('stringBool = : ' + stringBool);
console.log('stringBool Object 1 = : ' + stringBool[0]);
}
Thinking if I can get the complete string in the first object I can compare that to what I expect to see.
check this out
$('body').find('*:contains("Am I a String")').each(function(index, crntNode){
var parts = $(crntNode).text().split('?');
var flag = parts[1].trim();
alert(flag);
});
for example:
var a = $('div').text().match(/Am I a String\? (Yes|No)/g)[0];
var b = a.match(/(Yes|No)/g)[0];

JavaScript insert text after first parenthesis

everyone. I've got a string looks like
var s = "2qf/tqg4/ad(d=d,s(f)d)"
And I've got another string
var n = "abc = /fd/dsf/sdf/a.doc, "
What I want to do is insert n after the first '('
So it will look like
"2qf/tqg4/ad(abc = /fd/dsf/sdf/a.doc, d=d,s(f)d)"
Just use the replace function:
var result = s.replace("(", "("+n);
This barely needs REs.
var t = s.replace(/\(/, '('+n);
This doesn't need REs at all, as String.replace takes strings as well as REs to specify what should be replaced.
var t = s.replace('(', '('+n);

Fixing the URl so there is no spaces

I have a button that has its location generated dynamically via jquery:
<a id="final_location"
href="/pre_config/step4"
class="proceed-btn right">Proceed To Next Step >>></a>
$('#final_location').click(function() {
location.href = this.href + '/' + escape($('#type_of_station').html()) +
'/' + escape($('.number_changer').attr("id").slice(-1));
return false;
});
this works great but the problem comes into play when the html in type_of_station is two words... I get this url:
pre_config/step4/Pizza Delivery/2
Is there a way to make the url only give me the first word like this:
pre_config/step4/Pizza/2
maybe this can be changed to only return the first word?
Use
encodeURIComponent($('#type_of_station').text().match(/^\S*/)[0])
instead of escape($('#type_of_station').html()) to get the first word (separated by space).
This should get you the first word in the phrase:
var type = $('#type_of_station').html();
var i = type.indexOf(' ');
if (i != -1) type = type.substr(0, i);
You could do:
var name = "Pizza Delivery";
var pieces = name.split(" ");
alert(pieces[0]); // Pizza
Or just do:
var name = "Pizza Delivery";
name = name.replace(/\s/g, "-", name); // feel free to change the - delimiter
alert(name); // Pizza-Delivery

Categories

Resources