trouble with a search function - javascript

function Todo(id, task, who, dueDate) {
this.id = id;
this.task = task;
this.who = who;
this.dueDate = dueDate;
this.done = false;
}
// more code that adds the todo objects to the page and to the array todos
function search() {
for (var i = 0; i < todos.length; i++) {
var todoObj = todos[i];
console.log(todoObj.who); //shows both jane and scott
console.log(todoObj.task); // shows both do something and get milk
}
var searchTerm = document.getElementById("search").value;
searchTerm = searchTerm.trim();
var re = new RegExp(searchTerm, "ig");
var results = todoObj.who.match(re);
if (searchTerm == null || searchTerm == "") {
alert("Please enter a string to search for");
return;
} else {
alert(results);
}
}
This is a search function where I am trying to match what the user types into the search bar with objects that I have created earlier in the code. They must match the "who" and "task" parameters that I have given to the objects. So one object is who: jane task: do something and the other is who: scott task: get milk. The problem is, in my last alert I can only match scott and not jane. Scott is the last one I added. Is there some way I need to modify my loop or change my search criteria?

Your problem is that you are looping through the items, but then using todoObj after that loop. So todoObj will just hold the last item in the array. You need to reorganize a little...try something like this:
function search() {
var searchTerm = document.getElementById("search").value;
searchTerm = searchTerm.trim();
if (searchTerm == null || searchTerm == "") {
alert("Please enter a string to search for");
return;
} else {
var todoObj = undefined,
results = undefined,
re = new RegExp(searchTerm, "ig");
for (var i = 0; i < todos.length; i++) {
todoObj = todos[i];
results = todoObj.who.match(re);
if (results) {
alert("You found " + todoObj.who + ", who needs to " + todoObj.task + " by " + todoObj.dueDate);
return;
}
console.log(re.lastIndex);
}
alert("You didn't match anyone");
}
}
Here's an example of it working as I think you want it to: http://jsfiddle.net/sHSdK/2/

Related

How to find a word in a string?

The challenge is to "find Waldo." I'm trying to figure out how to find a word in a function/string." Return the index of where in the string 'Waldo' starts."
function findWaldo(str) {
var waldoPosition;
return waldoPosition
}
Simple task to do:
function findWaldo(str) {
return str.indexOf("waldo"); //the string you are looking for
}
It is explained quite well here.
There should be a library that does it easily, like string.indexOf, but you can do it manually with this algorithm:
int count = 0;
string yourText = "This is waldo?";
string toSearch = "waldo";
for (int x = 0; x < yourText.Lenght; x++)
{
if(yourText[x] == toSearch[0])
if((count + 1) == toSearch.Lenght)
return x;
else
count = 0;
//here we'd say ehh there's not Waldo on the string
}
To find a word or letter you can use x.indexOf method, hope to below code helps.
// Question
const findWord = (str, findWord) =>{
let total = ""
let error = false
let errorMessage = "";
if(str != null && str != ""){
error = false
if(!str.indexOf(findWord)){
total = `there is no ${findWord} in str peremeter.
`
}else{
total = `the position of ${findWord} is ${str.indexOf(findWord)}`
}
}else{
error = true;
errorMessage = "Please fill the str perimeter."
return errorMessage
}
return total
}
// Calling Function
console.log(findWord("Hello World", "World"))

Jquery check if array contains substring

I am trying to check if my array regions contains part of a string that users submit. In essence, this jquery script should check if the city that a user included in their address is one of the cities in the regions array.
For example, when a user enters Examplestreet 24 City1 and City1 is in the regions array, it should display a price of €40, else it should show €2/km.
I have the following code:
var regions = ["city1", "city2", "city3"];
var str = $("#addressField").val();
var address = str.toLowerCase();
var key, value, result;
for (key in regions) {
if (regions.hasOwnProperty(key) && !isNaN(parseInt(key, 10))) {
value = regions[key];
if (value.substring() === address) {
$("#deliveryPrice").text("€40");
}
else {
$("#deliveryPrice").text("€2/km");
}
}
}
This code is working fine when the string is just the city without the street or other characters, but it should also work if someone enters their full address. So I need to change my code so it searches the array regions for any part of the string address.
You can use regexp to find the right price:
var regions = ["city1", "city2", "city3"];
var address = "example address 42-200 City1 Poland";
var address2 = "city3";
var address3 = "city6";
function priceForAddress(address, regions) {
var city = regions.find(function (region) {
var reg = new RegExp(region, 'i');
return address.match(reg) !== null;
});
if (city) {
return '20$';
} else {
return '4$/km';
}
}
console.log(priceForAddress(address, regions));
console.log(priceForAddress(address2, regions));
console.log(priceForAddress(address3, regions));
You should just find if one of the cities is inside the string using indexOf
function test()
{
var regions = ["city1", "city2", "city3"];
var str = "Examplestreet 24 City1";
var address = str.toLowerCase();
var value, result;
for (value of regions) {
result = str.toLowerCase().indexOf(value);
console.log(result);
if (result !== -1)
{
console.log("$40");
return;
}
else
{
console.log("$2/km");
return;
}
}
}
test();

Array issues (javascript)

I created a small function that stores the book isbn, it's name and it's author. Everything is fine until I start to print out array. On every entery that completes the object into array, I want it to be printed one after another in new row, but this one is printing the objects from beginning every time when a new object is inserted. How do I fix this?
var books = [];
function blaBla(){
while(isbn != null || name != null || writer != null){
var isbn = window.prompt("Enter ISBN");
var name = window.prompt("Enter name of the book");
var writer = window.prompt("Enter name of the writer");
var patternString = /^[a-zA-Z]+$/;
var patternNum = /^[0-9]+$/;
if(isbn.match(patternNum)){
if(name.match(patternString)){
if(writer.match(patternString)){
books.push({
isbn: isbn,
name: name,
writer: writer
});
}
}
}
for (var i=0; i<books.length; i++){
document.write(books[i].isbn + " - " + books[i].name + " - " + books[i].writer + "</br>");
}
}
}
PS: How do I make it even more "cleaner", so when I hit cancel on prompt, it automatically stops with entering data into array, while, if i stop it on the "writer" prompt, it deletes previous entries for that object (last isbn and last name of the book)?
Thanks in advance.
You might want to give a little more context as to what this function is doing so we can help make your code cleaner as requested. I've separated the collection logic from the display logic here, and also used a while (true) loop with breaks on null or invalid inputs which will stop the collection of data.
Please note that prompt/alert boxes are a hideous way of collecting user input though (very awkward user experience). Consider using a table, input fields, and some jQuery instead to add rows and validate what the user has entered into input boxes.
var books = [];
function collectResponses() {
var patternString = /^[a-zA-Z]+$/;
var patternNum = /^[0-9]+$/;
while (true) {
var isbn = window.prompt("Enter ISBN");
if (!isbn || !isbn.match(patternNum)) {
break;
}
var name = window.prompt("Enter name of the book");
if (!name || !name.match(patternNum)) {
break;
}
var writer = window.prompt("Enter name of the writer");
if (!writer || !writer.match(patternNum)) {
break;
}
books.push({
isbn: isbn,
name: name,
writer: writer
});
}
}
function displayResponses() {
for (var i=0; i<books.length; i++){
document.write(books[i].isbn + " - " + books[i].name + " - " + books[i].writer + "</br>");
}
}

return a substring using indexOf as a parameter within a function

I'm supposed to create a functions to test a URL for validity then functions to look for and return parts of the URL string based on location of certain characters (position would be unknown). FYI, I'm very new to programming but have been searching and trying many answers. My latest attempt uses below format (found in an answer) but still can not get anything but an empty string to display when I call the function.
When I run this in Chrome, and enter "http://www.niagaracollege.ca" or "http://lego.ca" even though I am entering a valid URL, I get a return of false.
function validURL(userInput)
{
input = new String(userInput);
if (input.indexOf("://") != -1 && input.lastIndexOf(".") != -1)
return true;
else
return false;
}
function findProtocol(userInput)
{
input = new String(userInput);
var result = input.substring(0, input.indexOf("://"));
return result;
}
function findServer(userInput)
{
input = new String(userInput);
var result = input.substring(input.indexOf("://") + 1 ,input.lastIndexOf("."));
return result;
}
function findDomain(userInput)
{
input = new String(userInput);
var result = input.substring(input.lastIndexOf(".") + 1);
return result;
}
function btnReadURL_onclick()
{
var userInput = document.getElementById("txtURL").value;
var outputBox = document.getElementById("txtOutput");
var URL = validURL(userInput);
if (URL = true)
{
var Part1 = findProtocol(userInput);
var Part2 = findServer(userInput);
var Part3 = findDomain(userInput);
outputBox.value = "Protocol: " + Part1 + "\nServer: " + Part2 +
"\nDomain: " + Part3;
}
else (URL == true)
outputBox.value = "Invalid URL";
}
Use a debugger to find out what you are getting in the userInput. The code is fine. It should work. See sample code below.
test = function() {
var test = "http://Test 2"
alert(test.substring(0, test.indexOf("://")))
}
You need to pass the value to the findProtocol method rather than DOM element
Replace
var userInput = document.getElementById("txtURL");
by
var userInput = document.getElementById("txtURL").value;
and replace
if (URL = true)
with
if( URL == true )

Using separators in JS

I'm currently writing a program that uses ";" as a seperator and extracts the url up until that point upon searching the content.
So it has the format:
name;surname
In searching the given arrays... I decided to go the extra mile and test for arrays without the ";" but this has confused the program - it has no idea of the ";" position anymore and this throws a spanner in the works!
Here is my code so far - many thanks in advance!
pages =
[
"The first", "An;alternative;page", "Yet another page"
]
u_c_pages =
[
"www.cam.ac.uk;"+pages[0]
,
"www.warwick.ac.uk"+pages[1]
,
"www.kcl.ac.uk;"+pages[1]
,
"www;"+pages[2]
]
var pattern5 = prompt('5) Please enter a search term:');
function url1_m1(u_c_pages,pattern)
{
var seperator = [];
var seperatorPos = [];
if(pattern)
{
for (var i = 0; i < u_c_pages.length; i++)
{
var found = true;
if((u_c_pages[i].indexOf(";"))<0)
{
found=false;
}
else
{
seperator[seperator.length] = i;
seperatorPos[seperatorPos.length] = (u_c_pages[i].indexOf("|"));
}
}
if(seperator.length==0)
{
return("Nothing found!");
}
else
var found2 = "";
{
for (var j = 0; j < seperator.length; j++)
{
if(u_c_pages[j].substring(seperatorPos[j],u_c_pages[j].length-1).toLowerCase().indexOf(pattern.toLowerCase()) >= 0)
{
found2 = (u_c_pages[j].substring(0,seperatorPos[j]));
break;
}
}
return(found2)
}
}
else
{
// only returned when the user decides to type in nothing
return("Nothing entered!");
}
}
alert(url1_m1(u_c_pages,pattern5));
enjoy the power of regex:
on JSFiddle
pages = ["The first", "An;alternative;page", "Yet another page"];
u_c_pages = [
"www.lboro.ac.uk;"+pages[0],
"www.xyz.ac.uk;"+pages[1],
"www.xyz.ac.uk;"+pages[1],
"www;"+pages[2]
];
var pattern5 = prompt('5) Please enter a search term:');
function url1_m1(u_c_pages,pattern)
{
// escape search pattern
pattern = pattern.toLowerCase().replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
pattern = new RegExp('^([^;]+);.*?' + pattern, 'i');
var result = null;
for(var i=0;i<u_c_pages.length;i++) {
if((result = u_c_pages[i].match(pattern))) {
return result[1];
}
}
return false;
}
alert(url1_m1(u_c_pages,pattern5));
You can use String.split(";") to split a string into segments. The parameter is the seperator.

Categories