I am trying to make a translation app that can translate a number between 1-30 from english to its german/french counterpart. I think I am somewhat on the right track, ive made the arrays with all the translations, but the problems I am having is I don't know how to correlate the number the user puts in via a prompt, to one of the values in the array, example:
User is prompted for number between 1-30, user is prompted for language French/German = Translation
This is what I am trying to do. Bellow is what I have so far, feel free to nit pick, but bear in mind I am new to Javascript so there is probably a lot wrong.
function translate() {
if (lang = "French") {
console.log(frenchTranslation);
} else {
console.log(germanTranslation);
}
};
var x=translate
translate(x)
var number=(Number(prompt ("What is your number? Must be between 1-30")));
var lang=(prompt ("What is your language? Must be 'French' or 'German'. Case Sensitive."));
var frenchTranslation = ["Please enter a number between 1-30", "un","deux","trois","quatre","cinq","six","sept","huit","neuf","dix","onze","douze","treize","quatorze","quinze","seize","dix-sept","dix-huit","dix-neuf",
"vingt","vingt et un","vingt-deux","vingt-trois","vingt-quatre","vingt-cinq","vingt-six","vingt-sept","vingt huit","vingt-neuf","trente"];
var germanTranslation = ["Please enter a number between 1-30","Eins","Zwei","Drei","Vier","Fünf","Sechs","Sieben","Acht","Neun","Zehn","Elf","Zwölf","Dreizehn","Vierzehn","Fünfzehn","Sechzehn","Siebzehn","Achtzehn","Neunzehn",
"Zwanzig","Einundzwanzig","Zweiundzwanzig","Dreiundzwanzig","Vierundzwanzig","Fünfundzwanzig","Sechsundzwanzig","Siebenundzwanzig","Achtundzwanzig","Neunundzwanzig","Dreiβig"];
Right, so first of all, you need to add some input validation to know what the user has selected. I recommend storing it somewhere, then you should make sure that it's in the correct range. Just use an if statement to check if the number is >= 0 && <= 30. After that when you're trying to use console.log you need to use array index of the correct number.
Here's my solution, you can improve on it a lot.
var frenchTranslation = ["Please enter a number between 1-30", "un","deux","trois","quatre","cinq","six","sept","huit","neuf","dix","onze","douze","treize","quatorze","quinze","seize","dix-sept","dix-huit","dix-neuf",
"vingt","vingt et un","vingt-deux","vingt-trois","vingt-quatre","vingt-cinq","vingt-six","vingt-sept","vingt huit","vingt-neuf","trente"];
var germanTranslation = ["Please enter a number between 1-30","Eins","Zwei","Drei","Vier","Fünf","Sechs","Sieben","Acht","Neun","Zehn","Elf","Zwölf","Dreizehn","Vierzehn","Fünfzehn","Sechzehn","Siebzehn","Achtzehn","Neunzehn",
"Zwanzig","Einundzwanzig","Zweiundzwanzig","Dreiundzwanzig","Vierundzwanzig","Fünfundzwanzig","Sechsundzwanzig","Siebenundzwanzig","Achtundzwanzig","Neunundzwanzig","Dreiβig"];
function translate()
{
const yournumber = Number(prompt("Enter your number (1-30)"));
console.log(yournumber);
const language = prompt("Choose a language - German or French");
if(yournumber < 1 || yournumber > 30) {
alert("Too hard");
}
else {
if(language === "French") {
console.log(frenchTranslation[yournumber]);
}
if(language === "German") {
console.log(germanTranslation[yournumber]);
}
}
}
translate();
Related
To be honest, this sound like a duplicate post, but this is totally different from other post.
I'm building a chat room, where i would like to detect mobile number in user sending messages and warn the users that sending mobile numbers in the chat room is not safe and its against our policy.
There are few posts shows how to detect US number. But what about Indian numbers? they are 10 digit numbers.
var input = "hey im emily, call me now 9876543210"
I have to detect the number in all these formats.
9876543210
9 8 7 6 5 4 3 2 1 0
98765 43210
+919876543210
+91 9876543210
Some smart users always comes up with a smart way to come around those filters used in the client side javascript. So i have to be well prepared to detect all the method they use.
Example Message :
"hey this is emy, call me now 9876543210"
Expected output : pop up saying, hey buddy, sending numbers in the room is not safe and not allowed here.
Note: The string message should be allowed to send upoto 5 digit numbers, without getting the alert pop up. Or if you have any better idea? suggest me and we can make it work. Thanks
Here's a regex for a 7 or 10 digit number, with extensions allowed, delimiters are spaces, dashes, or periods:
^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$
Although you need to add conditions for special numbers like 911, 100, 101
In your test cases the length of phone number is 10:
So try the following code:
let input = "hey im emily, call me now 9 876543210";
let matched = input.match(/\d+/g).join('');
let phoneNumberLength = 10;
if (matched.length >= phoneNumberLength) {
console.log(`we've found a phone number. The number is ${matched}`);
} else
console.log(`The message does not contain phone number`);
Try to adjust this code as it is desired
UPDATE:
This code is intended to get desired results with test case by #tibetty:
let input = 'hi dude, please call my cell phone +86 13601108486 at 300pm"'
let matched = input.split(' ');
let maxIndex = matched.length - 1;
let filtered = matched.filter((s, i) => {
if (i != maxIndex && isNumeric(s) && isNumeric(matched[i + 1]))
return true;
if (isNumeric(s))
return true;
return false;
});
console.log(` The number is found ${filtered.join(' ')}`);
function isNumeric(n) {
return n.match(/^(?:[+\d].*\d|\d)$/);
}
try this one:
https://www.w3resource.com/javascript/form/phone-no-validation.php
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
I have been implementing a simple quiz for English. In that, we need to validate answers, which are entered by users in input field. In the current implementation, I am comparing the correct answer with user's answer exactly. Like,
HTML
<input type="text" id="answer" />
<button onclick="validate()">Validate</button>
Javascript
var question = "Do you like movies?",
answer = "No, I don't like movies.";
function validate() {
var userInput = document.getElementById('answer').value;
if(answer == userInput) {
console.log("correct");
} else {
console.log("wrong");
}
}
But I don't want validate exactly. Like, ignore case sensitive, commas, apostrophe, etc. For example if user enters,
i dont like movies
The answer can be correct. I don't know how start and where to start. Anyone please help.
One option would be to strip out all non-word characters and spaces, and compare the lower-case version of each replaced string:
var question = "Do you like movies?",
answer = "No, I don't like movies.";
const normalize = str => str
.replace(/[^\w ]/g, '')
.toLowerCase();
function validate(userInput) {
const noramlizedInput = normalize(userInput)
const noramlizedAnswer = normalize(answer);
if (noramlizedInput == noramlizedAnswer) {
console.log("correct");
} else {
console.log("wrong");
}
}
validate('No i dont like movies');
validate("NO!!!!! I DON''t like movies.");
Another option would be to loop through all possible substrings of the userInput and figure out which has the most overlap with the desired answer, but that's a whole lot more complicated.
An easier option would be to check to see how many overlapping words there are:
var question = "Do you like movies?",
answer = "No, I don't like movies.";
const normalize = str => str
.replace(/[^\w ]/g, '')
.toLowerCase()
.split(/\s+/)
function validate(userInput) {
const noramlizedInputArr = normalize(userInput);
const noramlizedAnswerArr = normalize(answer);
const overlapCount = noramlizedInputArr.reduce((a, word) => (
a + Number(noramlizedAnswerArr.includes(word))
), 0);
console.log(overlapCount);
if (overlapCount >= 4) {
console.log("correct");
} else {
console.log("wrong");
}
}
validate('No i dont like movies');
validate("NO!!!!! I DON''t like movies.");
validate("i dont like movies.");
validate("Yes I like movies.");
If you are interested in simply catching spelling errors and small variations, a standard metric is called edit distance or Levenshtein distance. This is a count of the minimum number of deletions, insertions, or substitutions you need to change one text into another. Strings like "No I don't like the movies" and "No I don't like the moveys" will have small edit distances.
Here's a quick and dirty recursive edit distance function that will give you an idea:
function validate(text, pattern) {
// some simple preprocessing
let p = pattern.toLowerCase().replace(/[^a-z]+/ig, '')
let t= text.toLowerCase().replace(/[^a-z]+/ig, '')
// memoize recursive algorithm
let matrix = Array.from({length: t.length + 1}, () => [])
function editDistance(text, pattern, i = 0, j = 0){
if(i == text.length && j == pattern.length) return 0
if(i == text.length) return pattern.length - j
if(j == pattern.length) return text.length - i
let choices = [
(matrix[i+1][j+1] || (matrix[i+1][j+1] = editDistance(text, pattern, i+1, j+1))) + (text[i].toLowerCase() === pattern[j].toLowerCase() ? 0 : 1),
(matrix[i+1][j] || (matrix[i+1][j] = editDistance(text, pattern, i+1, j))) + 1,
(matrix[i][j+1] || (matrix[i][j+1] = editDistance(text, pattern, i, j+1))) + 1
]
return Math.min(...choices)
}
return editDistance(t, p)
}
// similar strings have smaller edit distances
console.log(validate("No I dont lik moves","No i dont like movies"))
// a little less similar
console.log(validate("Yes I like movies","No i dont like movies"))
// totally different
console.log(validate("Where is the bathroom","No i dont like movies"))
// careful -- small edit distance !== close meaning
console.log(validate("I do like tacos","I don't like tacos"))
Picking a minimum acceptable distance works pretty well for matching strings with small typos. Of course, if you are trying to gauge user intent, none of these simple hues tics will work. Strings like "I love tacos" and "I loath tacos" have a small edit distance and you can't tell that they mean the opposite without knowledge of the language. If you need to do this level of checking you can try using a service like Watson Conversation that will return user intents to input.
There is a certain webpage which randomly generates a number, for example "Frequency : 21". I am trying to create a script which takes the number, 21, and compares it to another variable, then to an if else function. Basically, I've completed most of it, but I can't obtain the number 21. And since it is random, I can't put in a fixed value.
Can anyone help me out?
My code goes like:
setTimeout(MyFunction,5000)
function MyFunction(level,legmin) {
var level = x
var legmin = 49
if (level <= legmin) {
location.reload(true)
}
else {
alert("Met requirements.")
}
where the address of the text I want is:
html>body>div#container>div#contentContainer>div#content>
div#scroll>div#scrollContent>div>div>div#pkmnappear>form>p (x in the code above).
A quick-n-dirty solution without regex.
var lookFor = "Frequency : ";
var text = document.querySelector("#pkmnappear>form>p").textContent;
var level = text.substr(text.indexOf(lookFor) + lookFor.length).split(" ")[0];
This assumes the number will be followed by a space
I'm trying to allow my prices to display under 2 conditions
sales price must be less than the base price
"don't show pricing is unchecked" (yes or no) in our system
var basPrc = "$5000";
var onlnPrc = "<%=getAttribute('item','382798','salesprice')%>";
var CallForPrice = "<%=getAttribute('item','382798','dontshowprice')%>";
if (onlnPrc < basPrc || CallForPrice == "No") {
document.write('<span class="strike">Base Price: <span>'+basPrc+'</span></span>')
document.write("<br /><strong class=\"saleprice\">Our Price: <%=getAttribute('item','382798','salesprice')%></strong><br />");
//savings
var savings = onlnPrc - basPrc;
document.write ('<span class="save">You Save: <span class="red">'+ savings +'</span></span><br />');
}
//if don't show pricing is checked
if (CallForPrice = "Yes") {
var basPrc = null;
var onlnPrc = null;
document.write('<br /><strong class="saleprice">Call For Pricing<strong><br />');
}
//if no online pricing
else {document.write('<br /><strong class="saleprice">Our Price: '+basPrc+' <strong><br />');}
I tried the "&&" operators and no luck, any idea on what I should do next?
Your basPrc is a String, not a Number; you should initialize it to 5000, not "$5000" (the lack of quotes being important here). I'm not sure at all what onlnPrc will be. You need to make sure both are numbers. Otherwise, when you do basPrc > onlnPrc you will be doing a String comparison, not a numeric one.
// Base Price defaults to 5000
var basPrc = 5000;
// Parse the Online Price as a floating point number;
// if the result is NaN, default it to 0
var onlnPrc = parseFloat("<%=getAttribute('item','382798','salesprice')%>") || 0;
You should endeavor to make sure that basPrc and onlnPrc are always numbers since you are doing calculations with them. Leave the display of currency symbols or decimal points to the pieces of the code where you actually display the data.
Unrelated question: Where does this code live? What's it for? I've never seen NetSuite code that looked anything like this.
I still have a problem with jQuery code.
I want to check characters from strings which is in array while user typing something in the input. If any of first one characters is available in the array i want to display "VALID".
var postcodes = ["00-240","80","32","90","91", "8", "11"];
$('input[name="text-391"]').keyup(function(){
var val = this.value;
var m = $.map(postcodes,function(value,index){
var reg = new RegExp('^'+val+'.*$')
return value.match(reg);
});
if(m.length && val.length) {
$('#error').hide(300);
} else {
$('#error').show(300);
}
});
This code checks that all what user type in the input is in array, but i want to check this letter after letter.
For example:
user types: 0 - it's ok
user types: 00 - it's still ok
user types 00-340 - it's not ok and now I want to display warning that we haven't it in the array
user types: 3 - it's ok
user types: 35 - it's not ok, and now i want to display warning that we haven't it in the array
user types 80-125 - it's still ok [important]
user types 11-1 - it's still ok [important]
I will be very grateful for any tips. Regards
you need to add below code in $.map
if(val.length>2 && val.indexOf("-")>-1 && !(value.indexOf("-")>-1))
val= val.substring(0,val.indexOf("-"))
Here is the working DEMO
Explanation:
You just want to check if enter value length is more than two and it contains - and value in map should not contain -(you need last and condition for letter like "xx-xxx"
Thanks
You'll have to check it both ways:
var m = $.map(postcodes,function(value,index){
var reg = new RegExp('^'+val+'.*$')
var result=value.match(reg);
if (result.length) {
return result;
} else {
reg = new RegExp('^'+value+'.*$')
return val.match(reg);
}
});
You can optimize further if you first create an array of regex's based on postcodes and then reference them by index in the callback function.