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();
Related
What is the best way to target an array or a string, so that when a user types a letter it finds a match and logs the letter and its index in the array (or the string)?For example (set-up):
GUESS THIS MOVIE:
how to train your dragon
___ __ _____ ____ ______
Type a letter to guess, you have 10 TRIES:
User Typed: o
Result: _o_ _o _____ _o__ ____o_
HERES MY CODE:
var fs = require('fs');
var inquirer = require('inquirer');
var displayProgress = require('./checkGuess');
// var checkGuess = require('./checkGuess');
var PlayFunc = function() {
var blanksArr = [];
var currentWord = [];
this.getData = function() {
var stackOv = "";
fs.readFile("words.txt", "utf8", function(error, data){
if (error) throw error;
dataType = data.toLowerCase();
//data in array
var wordArr = dataType.split(',');
//select random from word from data
var compWord = wordArr[Math.floor(Math.random() * wordArr.length)];//random
//split chosen word
currentWord = compWord.split('');
console.log("========================\n\n\n");
//Looping through the word
for (var i = 0; i <= currentWord.length - 1; i++) {
// pushing blanks
var gArr = blanksArr.push("_");
//HYPHENS, COLONS, SPACES SHOULD BE PASSED
stackOv = currentWord.join("").replace(/[^- :'.]/g, "_");
wordString = currentWord.join("");
}
console.log("GUESS THIS MOVIE: ");
fs.writeFile("blanks.txt", stackOv, (err) => {
if (err) throw err;
console.log(wordString);
fs.readFile('blanks.txt', "utf8",(err, word) => {
if (err) throw err;
// console.log("GUESS THIS MOVIE: " + compWord);
blanksTxt = word.split(''); //console.log(string.join('').replace(/[^-: '.]/g, "_"));
displayProgress = new displayProgress();
displayProgress.checkGuess();
});
});
});
}
}
module.exports = PlayFunc;
ON THE NEXT FILE CALLED checkGuess.js I Plan to do the checking (which goes back to my original question (OP).
var fs = require('fs');
var inquirer = require('inquirer');
var PlayFunc = require('./PlayFunc');
var displayProgress = function (){
// console.log("WORKING CONNECTED CHECKGUESS MODULE");
// PlayFunc = new PlayFunc();
// PlayFunc.getData();
var a = blanksTxt.join(''); console.log(a); //string a
var manipulateThisArray = blanksTxt;//reading from blanks.txt
// console.log(manipulateThisArray);
this.checkGuess = function(){
inquirer.prompt([
{
type: "input",
name: "letter",
message: "Type a letter to guess, you have 10 TRIES:"
}
]).then(function(userInput) {
var correctArray = [];
// console.log(userInput.letter);
letterTyped = userInput.letter;
//logic
//test if we can parse through the array
for (var i = 0; i <= manipulateThisArray.length - 1; i++) {
x = manipulateThisArray[i]; console.log(x);
// if userinput letter-value matches chosen words letter value
// replace this chosen worsa letter with userinput value
// if(letterTyped == x.charAt(i)) {
console.log("THERES A MATCH " + x.charAt(i));
// }else {
// console.log("NO MATCH");
// }
}
});
}
}
// checkGuess();
module.exports = displayProgress;
//declaration of the variables we need
//the original string:
const string = "how to train your dragon";
//a string of characters we want to show
const show = "o";
//A resulting string we can work with
var result = "";
//Now we go over every character of our string and
for(const character of string){
//check if the character is inside the characters we want to show
if(show.includes(character)){
//if so we show it by adding it to the result
result += character;
}else{
//If not we add an _ instead
result += "_";
}
}
//At the end we can show the result
alert(result);
For this i would use the 'foo'.replace('bar', 'bar') and make sure that the String contains the input 'foo'.includes('input') also you could use a RegExp.
To get the index you could do a loop through the length of the String and use the 'foo'.indexOf('input', number) that will return -1 if no coincidence
I'm running an A/B test to see if showing more items is better for conversion. But it seems that the code sometimes causes errors.. But I can't find any errors and don't know when they occur.
In my test I check whether the url param IC exists and if it doesn't exists I will add this.
This is my code:
function checkIfAlreadyPaginated()
{
var field = 'IC';
var url = window.location.href;
if(url.indexOf('?' + field + '=') != -1)
return true;
else if(url.indexOf('&' + field + '=') != -1)
return true;
return false;
}
function insertParam(key, value) {
key = encodeURIComponent (key); value = encodeURIComponent (value);
var kvp = document.location.search.substr(1).split('&');
if (kvp == '') {
return '?' + key + '=' + value;
}
else {
var i = kvp.length; var x; while (i--) {
x = kvp[i].split('=');
if (x[0] == key) {
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if (i < 0) { kvp[kvp.length] = [key, value].join('='); }
return '?'+kvp.join('&');
}
}
var itemsPerPage = 48;
if(!checkIfAlreadyPaginated())
{
document.location.search = insertParam('IC', itemsPerPage);
}
Does someone spot possible issues? I'm running the test via VWO.com.
If there is a Javascript error you should see it in the browser console and share it with us.
In any case, I would do it by creating a JS Object first. I find it easier to work with.
In the following code I added the option to do the checking for multiple params of the querystring. If you only need to check the IC you can simplify it a bit. I tested it on a blank test.html.
<script type="text/javascript">
// get the current params of the querystring
var querystringItems = document.location.search.substr(1).split('&');
// create an object
var querystringObject = {};
for(i=0;i<querystringItems.length;++i) {
param = querystringItems[i].split('=');
querystringObject[param[0]] = param[1];
}
// Define the keys to be searched for and their default value when they are not present
var requiredKeys = {"IC":48, "test": "me"};
// Do the checking on the querystringObject for each requiredKeys
var doreload = false;
for (var key in requiredKeys) {
if (typeof querystringObject[key] == 'undefined') {
doreload = true;
// Create the missing parameter and assign the default value
querystringObject[key] = requiredKeys[key];
}
}
// If any of the requiredKeys was missing ...
if (doreload) {
// rebuild the querystring
var querystring = '?';
for (var key in querystringObject) {
querystring+=key+'='+querystringObject[key]+'&';
}
querystring=querystring.substr(0,querystring.length-1);
// reload page
document.location.search = querystring;
}
// assign the values to javascript variables (assuming you had it like this because you needed it)
var itemsPerPage = querystringObject.IC;
</script>
Here is an example to check this:
//get URL params into string:
paramStr = window.location.substring(window.location.indexOf('?'), window.location.length;
//turn string into array
paramArray = paramStr.split('&');
//prepare final array of params
params = {};
//prepare the index of IC parameter
icLoc = -1; //this is negative 1 so that you know if it was found or not
//for each item in array
for(var i in paramArray){
//push its name and value to the final array
params.push(paramArray[i].split('='));
//if the parameter name is IC, output its location in array
if(params[i][0] === 'IC'){
icLoc = i;
}
}
If IC is not found, icLoc will be -1.
If it is found, the value of IC in the URL parameters is params[icLoc][1]
Example result for query string ?foo=bar&code=cool&IC=HelloWorld:
params = {'foo': 'bar', 'code': 'cool', 'IC': 'HelloWorld'}
icLoc = 2
Example for query string ?foo=bar&code=cool:
params = {'foo': 'bar', 'code': 'cool'}
icLoc = -1
Here id is the param I'm using for a test. Pass the argument which you want to check whether it exists or not.
function queryParamExistUrl(param = '') {
if (new URLSearchParams(window.location.search).get(param) != null)
return true
return false
}
console.log(queryParamExistUrl('id'))
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 )
I would like to display a message on the page based on some value appearing in the URL. I have a known list of strings I'm looking for and the corresponding message. I cannot seem to get anywhere with the lookup / messaging. Could anyone pls kindly help? JavaScript only preferred, not jquery. Not that I the difference at this point ;)
Many thanks!
<div id="messagediv"></div>
Sample URLs to test:
<p>Campaign 1
<p>Campaign 2
<p>Campaign 3
<script>
(function () {
var params = window.location.search.substring(1).split('&'),
urlParams = {},
key, val;
for (var i = 01; i < params.length; i++) {
urlParams[params.split('=')[0]] = params.split('=')[1];
}
// querystring is ?utm_campaign=SpaCamp12458
// for instance, match URL query value SpaCamp12458 with the nums SpaComp key and show the corresponding text in the messagediv
var nums = {
defaultMessage: "Default Message",
"SpaComp": "Spas",
"PoolComp": "Recreation",
"BeachComp": "Outdoors"
}
for (var i in nums) {
if (nums.hasOwnProperty(i)) {
var found = false;
for (var j in urlParams) {
if (urlParams.hasOwnProperty(j)) {
if (urlParams[j].indexOf(nums[i]) === 0) {
document.getElementById("messagediv").innerHTML = nums[i];
found = true;
break;
}
}
}
if (!found) {
document.getElementById("messagediv").innerHTML = nums.defaultMessage;
}
}
}
})();
</script>
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/