How do I create a simple search function in javascript? - javascript

I start with a short array of some schools and then I want to test if the value of an input matches one of these schools.
Here is my code thus far:
var $schools = [
'University of Tennessee-Knoxville',
'Maryville College',
'Cleveland State Community College',
'East Tennessee State University'
];
var $searchBar = $('input.searchBar');
$searchBar.keyup(function(){
var $searchValue = $searchBar.val();
for (var x = 0; x < $schools.length; x++) {
var $schoolLC = $schools[x].toLowerCase();
var $searchLC = $searchValue.toLowerCase();
var $searchingValue = new RegExp('.*' + $searchLC + '.*');
if ($schoolLC.match($searchingValue)) {
console.log($searchLC);
}
}
});
But something is obviously wrong (I believe with my RegExp), because it never console.logs the $searchLC.
Thanks so much!!

Isn't this
if ($searchLC.match($searchingValue)) {
supposed to be
if ($schoolLC.match($searchingValue)) {

I think you need to escape all RegEx special characters:
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
...
var $searchingValue = new RegExp('.*' + escapeRegExp($searchLC) + '.*');
...

Try this out: Live Demo
for (var x = 0; x < $schools.length; x++) {
var $schoolLC = $schools[x].toLowerCase();
var $searchLC = $searchValue.toLowerCase();
var $searchingValue = new RegExp('.*' + $searchLC + '.*');
if ($schoolLC.match($searchingValue)) {
alert($schoolLC);
}
}

Well, for this particular example, instead of using match you can use indexOf so that your code becomes
var $schools = [
'University of Tennessee-Knoxville',
'Maryville College',
'Cleveland State Community College',
'East Tennessee State University'
];
var $searchBar = $('input.searchBar');
$searchBar.keyup(function(){
var $searchValue = $searchBar.val();
for (var x = 0; x < $schools.length; x++) {
var $schoolLC = $schools[x].toLowerCase();
var $searchLC = $searchValue.toLowerCase();
if ($schoolLC.indexOf($searchLC) >= 0) {
console.log($searchLC);
}
}
});

Related

Certain number question being missed in regex

I have the following if statement that removes the first instances of a number followed by the period. However, I am noticing it is missing to catch some of them (ex. "16.", "23.", "24.", etc.) and not sure why.
Here is the function:
function quesCleanUp(ques){
//Checks the first instance of "." and removes it and the number
if(ques.match(/[0-9]\./g)?.length > 1){//(ques.match(/./g)?.length > 1){
var quesClean = ques.replace(/^[^\.]*\./, '').trim();
} else{
var quesClean = ques.trim();
}
return quesClean;
}
The following for loop extracts the question from the google form:
for (var i = 0; i < items.length; i++) {
var item = items[i];
switch(item.getType()) {
case FormApp.ItemType.MULTIPLE_CHOICE:
var question = item.asMultipleChoiceItem();
var ques = quesCleanUp(question.getTitle().trim());//replace(/\s/g, "");
var question_type = "Multiple Choice";
var optns = [];
var answr;
var answers = question.getChoices();
answer_val = false;
for (var j = 0; j < answers.length; j++) {
var clean = answers[j].getValue().trim();
optns.push(clean);
if(answers[j].isCorrectAnswer()){
answr = answers[j].getValue().trim();
for(var x = 0; x < optns.length; x++){
if(answr == optns[x]){
answer_val = true;
break;
}
}
}
}
var multiJSON = makeJSON(ques, question_type, optns, answr);
console.log("JSON1: " + JSON.stringify(multiJSON));
constructedJSON[i+1] = multiJSON;
break;
case FormApp.ItemType.CHECKBOX:
var question = item.asCheckboxItem();
//var ques = question.getTitle().trim();//.replace(/\s/g, "");
var ques = quesCleanUp(question.getTitle().trim());//replace(/\s/g, "");
var question_type = "CheckBox";
var optns = [];
var answr = [];
var answers = question.getChoices();
for (var j = 0; j < answers.length; j++) {
var clean = answers[j].getValue().trim();//replace(/\s/g, "");
optns.push(clean);
if(answers[j].isCorrectAnswer()){
answr.push(answers[j].getValue().trim());
}
}
var checkJSON = makeJSON(ques, question_type, optns, answr);
console.log("JSON2: " + JSON.stringify(checkJSON));
constructedJSON[i+1] = checkJSON;
break;
case FormApp.ItemType.PARAGRAPH_TEXT:
var question = item.asParagraphTextItem();
//var ques = question.getTitle().trim();//.replace(/\s/g, "");
var ques = quesCleanUp(question.getTitle().trim());//replace(/\s/g, "");
var question_type = "free response";
var optns = [];
var answr;
var paraJSON = makeJSON(ques, question_type, optns, answr);
console.log("JSON3: " + JSON.stringify(paraJSON));
constructedJSON[i+1] = paraJSON;
break;
case FormApp.ItemType.TEXT:
var question = item.asTextItem();
//var ques = question.getTitle().trim();
var question_type = "free response";
var ques = quesCleanUp(question.getTitle().trim());//replace(/\s/g, "");
var optns = "";
var answr = "";
var textJSON = makeJSON(ques, question_type, optns, answr);
console.log("JSON4: " + JSON.stringify(textJSON));
constructedJSON[i+1] = textJSON;
break;
}
The following example is the type of question 16. What is the meaning of life?
And the expected output: What is the meaning of life?
Try using /[0-9]+./g to catch more than one digit
As a quick fix, in the function quesCleanUp() try to change the line:
if(ques.match(/[0-9]\./g)?.length > 1){//(ques.match(/./g)?.length > 1){
With:
if (ques.match(/^[0-9]+\./g).length > 0) {
I suspect you got the downvotes because you posted the code with glared typos. It looks like you didn't even try to debug it first. And as the icing on the cake you accepted a wrong answer.
And probably the function can be boiled down to just one line:
const quesCleanUp = q => q.replace(/^\d+\./,'').trim();
Here is how it works:
var questions = ['1. aaa', '16. What', '23. That', 'No nums'];
const quesCleanUp = q => q.replace(/^\d+\./,'').trim();
questions.forEach(q => console.log(quesCleanUp(q)));
Expected output:
aaa
What
That
No nums

trying to get a rocket to run (doesnt work :()

So i'm currently partaking in some tasks for my school and then i came across one of them which got me a bit confused! We are asked to make the rocket launch however i am confused on how i would go about this. Hopefully, you can help me do this and thanks for reading.
// Launch the rocket!
var launchRocket = function (sequence) {
if (sequence != 321) {
var _$_f307 = ["\x63\x6C\x61\x73\x73\x4E\x61\x6D\x65", "\x61\x6E\x69\x6D\x61\x74\x69\x6F\x6E\x2D\x77\x69\x6E\x64\x6F\x77", "\x67\x65\x74\x45\x6C\x65\x6D\x65\x6E\x74\x73\x42\x79\x43\x6C\x61\x73\x73\x4E\x61\x6D\x65", "\x62\x6F\x64\x79", "\x61\x6E\x69\x6D\x61\x74\x69\x6F\x6E\x2D\x77\x69\x6E\x64\x6F\x77\x20\x61\x6E\x69\x6D\x61\x74\x65", "\x66\x69", "\x72\x33\x61", "\x77\x61\x79", "\x69\x6E\x6E\x65\x72\x48\x54\x4D\x4C", "\x72\x6F\x63\x6B\x65\x74\x2D\x63\x6F\x64\x65"];
document[_$_f307[3]][_$_f307[2]](_$_f307[1])[0][_$_f307[0]] = _$_f307[4];
var e = _$_f307[5];
var x = _$_f307[6];
var n = _$_f307[7];
document[_$_f307[3]][_$_f307[2]](_$_f307[9])[0][_$_f307[8]] = e + x + n;
}
}
All these \xXX are Hex codes of letters. Just decode them to see
var _$_f307 = [//create array
"className", //[0]
"animation-window",
"getElementsByClassName",
"body",
"animation-window animate",
"fi",
"r3a",
"way",
"innerHTML",
"rocket-code" //[9]
];
//then replace other cipher with values
//document[_$_f307[3]][_$_f307[2]](_$_f307[1])[0][_$_f307[0]] = _$_f307[4];
document["body"]["getElementsByClassName"]("animation-window")[0]["className"] = "animation-window animate";
var e = _$_f307[5]; //fi
var x = _$_f307[6]; //r3a
var n = _$_f307[7]; //way
//document[_$_f307[3]][_$_f307[2]](_$_f307[9])[0][_$_f307[8]] = e + x + n;
document["body"]["getElementsByClassName"]("rocket-code")[0]["innerHTML"] = e + x + n; //fir3away
Note that you can address JS object properties using dot . or bracket [] syntax.
So add rocket launcher ;)
<div class="animation-window"></div>
<div class="rocket-code"></div>
Update See working example
// Launch the rocket!
var launchRocket = function(sequence) {
if (sequence != 321) {
var _$_f307 = ["\x63\x6C\x61\x73\x73\x4E\x61\x6D\x65", "\x61\x6E\x69\x6D\x61\x74\x69\x6F\x6E\x2D\x77\x69\x6E\x64\x6F\x77", "\x67\x65\x74\x45\x6C\x65\x6D\x65\x6E\x74\x73\x42\x79\x43\x6C\x61\x73\x73\x4E\x61\x6D\x65", "\x62\x6F\x64\x79", "\x61\x6E\x69\x6D\x61\x74\x69\x6F\x6E\x2D\x77\x69\x6E\x64\x6F\x77\x20\x61\x6E\x69\x6D\x61\x74\x65", "\x66\x69", "\x72\x33\x61", "\x77\x61\x79", "\x69\x6E\x6E\x65\x72\x48\x54\x4D\x4C", "\x72\x6F\x63\x6B\x65\x74\x2D\x63\x6F\x64\x65"];
console.log(_$_f307);
document[_$_f307[3]][_$_f307[2]](_$_f307[1])[0][_$_f307[0]] = _$_f307[4];
var e = _$_f307[5];
var x = _$_f307[6];
var n = _$_f307[7];
document[_$_f307[3]][_$_f307[2]](_$_f307[9])[0][_$_f307[8]] = e + x + n;
}
}
//Call the function
//launchRocket(0);
.animate {
background: red
}
<div class="animation-window">Will be red</div>
<div class="rocket-code">code</div>
<button type="button" onclick="launchRocket(0);">Launch!</button>

How to search for an array of patterns in another array using Google Script?

Using two arrays, I want to find patternArray[] items in myArray[].
If there is a match, I want to add the match from myArray to foundArray.
My current code gives me the following error;
TypeError: Cannot call method "search" of undefined. (line
could any one tell me how to fix the above error ?Furthermore, Does this solution find multiple matches in myArray ?
(for example if "red apple"(from patternArray) found more then once in myArray i want to add both to foundArray.)
function findpattern()
{
var foundArray=[];
var NotfoundArray=[];
var foundStringCounter=0;
var NotfoundStringCounter=0;
var myArray=["red apple http://awebsite.com/1.jpg","green apple http://1awebsite.com/2.jpg","red apple http://1awebsite.com/3.jpg"];
var patternArray= ["green apple","red apple","mango","orange tree","cherry tree","banana store","grape tree"];
var patternArraySize = patternArray.length;
for (var i = 0; i < patternArraySize; i++)
{
var result = myArray[i].search(patternArray[i]);
//var result = myArray[i].indexOf(patternArray[i]);
if (result == -1) {
NotfoundArray.push(myArray[i]);
NotfoundStringCounter++;
} else {
foundArray.push(myArray[i]);
foundStringCounter++;
}
result="";
}
Logger.log(foundStringCounter);
Logger.log(foundArray);
Logger.log(NotfoundStringCounter);
Logger.log(NotfoundArray);
}
This code works:
function findpattern() {
var foundArray=[],
NotfoundArray=[],
foundStringCounter=0,
NotfoundStringCounter=0;
var myArray=["red apple http://awebsite.com/1.jpg",
"green apple http://1awebsite.com/2.jpg",
"red apple http://1awebsite.com/3.jpg",
"rotten apple http://rottenApple.com"];
var patternArray= ["green apple","red apple","mango","orange tree","cherry tree","banana store","grape tree"];
var patternArraySize = patternArray.length;
Logger.log('patternArraySize: ' + patternArraySize);
var i=0,
j=0,
thisUrl="",
thisPattern="",
isMatched=0,
outerArray = [];
for (i=0; i < myArray.length; i++) {
thisUrl = myArray[i];
foundStringCounter = 0; //Reset
temporaryArray = []; //Reset
for (j=0; j<patternArraySize; j+=1) {
thisPattern = patternArray[j];
isMatched = thisUrl.indexOf(thisPattern);
if (isMatched !== -1) {
foundArray.push(thisUrl);
foundStringCounter++;
};
};
if (foundStringCounter===0) {
NotfoundArray.push(thisUrl);
};
outerArray.push(foundArray);
};
Logger.log('foundArray: ' + foundArray);
Logger.log('NotfoundArray: ' + NotfoundArray);
Logger.log('outerArray: ' + outerArray);
};
var currentSheet = SpreadsheetApp.getActiveSheet();
currentSheet
.getRange(currentSheet.getLastRow()+1, 1,outerArray.length,foundArray.length)
.setValues(outerArray);

JS: Create Objects in loop with iterator

I want to create some objects like object_point1, object_point2, ...
with a for loop that split a string with x and y coords.
How can i use iterates to create the name of objects?
Thanks
var vMsg = req.body.myMessage;
var fields = vMsg.split(/\n/);
var myobjct = new Object();
myobject.PointCount=parseFloat(paramsCoords);
for (var ii=0; ii<fields.length; ii++)
{
var coord=fields[ii].split(/\t/);
//console.info ("X" + coord[0]);
//console.info ("Y" + coord[1]);
var object_Point[ii] = new Object();
object_Point[ii].x_m=parseFloat(coord[0]);
object_Point[ii].y_m=parseFloat(coord[1]);
myobject.Polygon_Point[ii]=object_Point[ii];
}
At the moment i use this construction:
for (var ii=0; ii
var coord=fields[ii].split(/\t/);
var objPolygon_Point = new Object()
objPolygon_Point["point" + ii] = new Object();
objPolygon_Point["point" + ii].x_m=parseFloat(coord[0]);
objPolygon_Point["point" + ii].y_m=parseFloat(coord[1]);
if (ii=='1')
{
myobject.Polygon_Point1=objPolygon_Point["point" + ii];
}
if (ii=='2')
{
myobject.Polygon_Point2=objPolygon_Point["point" + ii];
}
// ii==3, ii==4, .......
}
You can generate dynamic object names in the global scope like:
Browser:
var ii = 11
, x = 123
, y = 234;
window['Object_Point' + ii] = {
x : parseFloat(x),
y : parseFloat(y)
}
console.log(Object_Point11);
console.log(window.Object_Point11);
// Object {x: 123, y: 234}
node.js
> var i = 12;
> global['MyObj'+i] = { hello : 'world' };
> console.log(MyObj12);
> console.log(global.MyObj12);
// { hello: 'world' }
see node.js global variables?
But rather than using window or global, you might want to use your own object
> var i = 12, myObj = {};
> myObj['MyObj'+i] = { hello : 'world' };
> console.log(myObj.MyObj12);
// { hello: 'world' }
I directly used your example. I'll suggest to create middle-map object. I.e. something like holder of all the points. Using the global namespace is not a good practice.
var vMsg = req.body.myMessage;
var fields = vMsg.split(/\n/);
var myobjct = new Object();
myobject.PointCount=parseFloat(paramsCoords);
var points = {};
for (var ii=0; ii<fields.length; ii++)
{
var coord=fields[ii].split(/\t/);
//console.info ("X" + coord[0]);
//console.info ("Y" + coord[1]);
var point = points["point" + ii] = new Object();
point.x_m = parseFloat(coord[0]);
point.y_m = parseFloat(coord[1]);
myobject.Polygon_Point[ii] = point;
}

Populating an array of objects in javascript

Let us say I have an object Airport with members airportCode and airportCity like this:
function Airport(airportCode, airportCity) {
this.airportCode = airportCode;
this.airportCity = airportCity;
};
How can I create an array of objects Airport to which I can add. In Java, this would work like this:
while(st.hasMoreTokens()) {
Airport a = new Airport();
a.airportCode = st.nextToken();
a.airportCity = st.nextToken();
airports.add(a);
}
A very short answer:
airports.push(new Airport("code","city"));
Try this:
function Airport(airportCode, airportCity) {
this.airportCode = airportCode;
this.airportCity = airportCity;
};
var dataArray = [];
for(var i=0; i< 10; i++){
dataArray[i] = new Airport("Code-" + i, "City" + i);
}
It's not really that different
var airports = [];
while (st.hasMoreTokens()) {
var a = new Airport();
a.airportCode = st.nextToken();
a.airportCity = st.nextToken();
airports.push(a);
}

Categories

Resources