My code isn't working, can someone please tell me what the problem is?
I'm guessing it's the for loop, but I cannot find the problem.
<html>
<body>
<script>
username = prompt("Please enter a your username:");
for (var i = 0; i < username; i++) {
if(isFinite(username.charAt(i))) {
result = true;
document.write("The username consists of one or more numbers." + BR);
}
else {
result = false;
document.write("The username must consist of one or more numbers." + BR);
}
}
</script>
</body>
</html>
You have two problems in your code:
In the for loop, use the length of the variable to establish the stop condition
for (var i = 0; i < username.length; i++)
BR is not defined
Working code: http://jsfiddle.net/f643fr4w/
From the output I can probably assume you just want to check if username consists of at least one number, actually: a digit.
// iterate over the input
for (var i = 0; i < username.length; i++) {
// check if it is a number (not a digit but that's the same here)
if (isFinite(username.charAt(i))) {
result = true;
// The requirement "one or more numbers" is fulfilled,
// we can break out of the loop
break;
}
else {
result = false;
}
// print something according to "result"
if(result === true){
document.write('The username consists of one or more numbers.');
} else {
document.write('The username must consist of one or more numbers.');
}
}
You have to go over the full length of the string to find out if there's no number but not if you want to find out if there is any number in it.
Now, if you want to test if it consists of only digits you have to reword the requirements, they are a bit too ambiguous now.
Additional hints:
you need to check the input, you always have to check user input!
you need to be aware that JavaScript strings are UTF16. Rarely a problem but gets easily one if you iterate over JavaScript strings.
String.charAt() returns a character, not a number. Don't rely on the automatic conversions in JavaScript, you way too easily shoot yourself in the foot if you rely on it but also if you don't, so be careful.
please don't use document.write, use either the console if available or change the text-node of an HTML element.
With these points in mind you may get something like this:
// make a list of digits
var digits = ['0','1','2','3','4','5','6','7','8','9'];
// ask the user for a username
var username = prompt("Please enter a your username:");
// check input
if (username.length === 0) {
console.log('no username given');
} else {
for (var i = 0; i < username.length; i++) {
// indexOf searches for the same type, that's why the digits above
// are strings with quotes around them
if (digits.indexOf(username.charAt(i)) >= 0) {
result = true;
// The requirement "one or more numbers" is fullfilled,
// we can break out of the loop
break;
}
else {
result = false;
}
}
// print something according to "result"
if (result === true) {
console.log('The username consists of one or more numbers.');
} else {
console.log('The username must consist of one or more numbers.');
}
}
The above is one variation of many and could easily give rise to a heated discussion on some forums (not here! Of course not! ;-) ) but I hope it helps.
Use a regex for such shenanigans:
var username = prompt("username plz kk thx");
var result = /[0-9]/.test(username);
document.write("The username " + (result ? "consists" : "must consist") + " of one or more numbers");
Related
I wrote this code for the user to guess a password exactly 4 times but I am not able to compare the input with the pin, is the way I have compared here wrong? can I not compare the number directly? like
if (input !== 0704)
is it wrong if I'm writing the number directly like this? it works fine if I replace the number with a string.
let pin = 0704;
let count = 0;
for (i=1; i<=4; i++) {
let input = prompt('please make a guess');
if (input !== 0704 ) {
console.log('Sorry that was wrong');
count++;
}
else {
console.log('That was correct!')
break;
}
}
if by input you are meaning html input then you need to compare the value with a string since output of html input is in string format. Also note the preceding 0 in 0704 will be ignored. So in this case you can use 0704 as string and perform comparison
let pin = '0704';
let count = 0;
for (i = 1; i <= 4; i++) {
let input = prompt('please make a guess');
if (input !== pin) {
console.log('Sorry that was wrong');
count++;
} else {
console.log('That was correct!')
break;
}
}
With number, input 0704 / 000704 has same value.
It must be a "String".
So my code currently only puts -boink or -bork after the entire string once the conditions are met but I want it so that after every single word the terms get added based on whether or not it satisfies the conditions of being either greater or less than five characters.
For example "My-boink name-boinkk is-boink Emmanuel-bork"
function myFunctionOne(input1, input2) {
var prompt1 = prompt("Please enter 1, 2, 3, or Exit").toLowerCase();
var prompt2 = input2;
if (prompt1 == 1) {
prompt2 = prompt("Please enter a string");
while (prompt2.length === 0) {
prompt2 = prompt("You need to enter something");
}
myFunctionOne(prompt1, prompt2);
}
if (prompt1 == 2) {
if (prompt2.length > 5) {
console.log(prompt2 + "-bork");
}
myFunctionOne(prompt2);
}
else {
console.log(prompt2 + "-boink")
}
}
myFunctionOne(1, 2, null);
You need to split the string into words with the split method and then loop through them using a for loop to check if they're longer than 5 characters and add 'bork' or 'boink' and then join the words again.
I could write the code for you, but I think it will be more satisfying for you to do it yourself. If you want me to write it thought let me know.
Edit
I'm going to write the code as close as what you already have as posible
function myFunctionOne(input1, input2) {
var prompt1 = prompt("Please enter 1, 2, 3, or Exit").toLowerCase();
var prompt2 = input2;
if (prompt1 == 1) {
prompt2 = prompt("Please enter a string");
while (prompt2.length === 0) {
prompt2 = prompt("You need to enter something");
}
myFunctionOne(prompt1, prompt2);
}
if (prompt1 == 2) {
var words = prompt2.split(" "); // we separate the string into words dividing them by space into an array called words
for(var i = 0; i < words.length; i++){ // we loop from 0 to the length of the array - 1 to access all positions in the array (the last position in arrays are always the length of the array - 1 because they start at 0)
if(words[i].length > 5){ //we check if the word in this position of the array is longer than 5 characters
words[i] += "-bork"; //if it is we add -bork
}else{
words[i] += "-boink" //if it is not longer than 5 characters we add -boink
}
}
console.log(words.join(" ")); //we print the array joining the elements with an space to form a string
}
}
myFunctionOne(1, 2, null);
I'm a little confused by what's going on at the top of your code, so I'm not going to refactor the entire thing. I'm going to provide an explanation from the time we have our string.
One approach would be to use .split(), which will return an array of string values based on what character you choose to split the string by. The reason we need to do this is because your code is currently looping through each string, rather than each word in the string. In this instance, I'm assuming your string can't take punctuation like commas or periods. If that's the case, you want to split by empty spaces, so it would look like string.split(" ").
Then, you could use the map() array method to loop through every value in the array and perform a function on it. Note, the map() method will return a new array, so best to save this into a new variable.
Then, you could use the .join() method, which will join the values of an array based on some value (essentially the opposite of .split()). Again, assuming no punctuation, I'd join the array with a space so that the values have a space between them, which would look like array.join(" ").
I've included some mock code below.
const string = prompt("Please enter your string");
const stringToArray = string.split(" ");
console.log(stringToArray);
const filteredArray = stringToArray.map((string) => {
if (string.length > 5) {
return string + "-bork";
}
return string + "-boink";
});
console.log(filteredArray);
const joinedFilteredArray = filteredArray.join(" ");
console.log(joinedFilteredArray);
I am writing a function that will evaluate expressions in an input field and return the sum.
Currently is working but I am running into an error that I just cannot figure out. Here is my code in Plunker.
function linkFunction(scope) {
var PO = 10;
scope.value = PO;
scope.result = '';
scope.Evaluate = function (input) {
if (input.match(/[a-zA-Z]/g) != null) { //to check if user has inputted a letter between a-z, case sensitive.
return alert("You must only use numbers, not letters")
} else if (input.match(/[!"^£$&[{}\]?\\##~<>_'|`¬:;,=]/g) != null) { //to check if user has inputted a special symbol
return alert("You must only use the symbols specified")
} else if (input.match(/\.\d*\.+/g) != null) { //to check if user has inputted a doubled decimal eg 10.2.2
return alert("You can only use 1 decimal point")
} else if (input.match(/\.{2,}/g) != null) {//to check if user has inputted a two decimals eg 10..1
return alert("You cannot put two decimals one after another")
}
// if (input.match(/\d*\(\d\W\d\)/g) != null){
// }
var percentPattern = /[0-9]*\.?[0-9]+%/g;
var expressionResults = input.match(percentPattern);
if (scope.enablePercentage) { //if parameter = 1, then do this code.
if (expressionResults != null) { //if user has entered into the input field
if (expressionResults.length > 1) { //if you user has finished the RegEx (%, is the end of the RegEx, so code will think its the end of the array, therefore you cannot add another %)
return alert("Too many % values");
} else {// user has met all requirements
var percentageValue = parseFloat(expressionResults) * PO / 100;
input = input.replace(expressionResults, percentageValue);
}
}
} else if (expressionResults != null) { //if parameter = 0, then do this code. Parameter is off, but user has entered percentage
return alert("You cannot use %");
}
scope.result = eval(input);
}
}});
If you write 10(5+3) it gives you an error
TypeError: 10 is not a function
Obviously if a user ran this code they would expect to see the value 80.
Eval thinks that 10() is a function.
Does anyone know how to fix this problem. Thanks
eval expects you to pass it JavaScript, not algebra.
If you want to multiply two values together then you must use a Multiplicative Operator.
10 * (5+3)
Thanks for your help with my earlier question:
How to find all instances and display in alert
Now I discover that I need to include some invalid character validation.
I'm trying to figure out how to include a set of regex invalid characters as part of the validation that will also show up in the same alert/textbox/whatever as the "too long/too short" validation.
So, I have a textbox which users will type or paste comma separated values such as AAAAAAA,BBBBBBB,CCCCCCCC,DDDDDDDD
And they cannot be more or less than seven characters long and they can only include certain characters.
I currently have have two separate pieces of Javascript that I'm trying to now combine:
var Invalidchars = "1234567890!##$%^&*()+=[]\\\';./{}|\":<>?";
for (var i = 0; i < document.getElementById("TextBox1").value.length; i++) {
if (Invalidchars.indexOf(document.getElementById("TextBox").value.charAt(i)) != -1){
alert
and this
var val = document.getElementById("Textbox1").value,
err = $.grep(val.split(','), function(a) { return a.length != 7; });
if (err.length) {
alert("All entries must be seven (7) characters in length. Please correct the following entries: \n" + err);
return false;
}
return true;
Any help is much appreciated!
=================================================
SOLUTION
Took a while, but using Tenub's code (which didn't quite combine my two sets code, but was close enough), I finally figured out how to merge my two sets of code into one. Here's the code if anyone is ever interested in using it:
var val = document.getElementById("TextBox1").value,
err = $.grep(val.split(','), function(a) {return (a.length = (!/^[^0-9!##$%^&*()+=;.\/\{}|:<>\\?\[\]\'\"]{7}$/.test(a)));});
if (err.length){
document.getElementById("DIV1").style.display = "inline-block";
document.getElementById("TextBox2").value = err.join(',');
return callback (false);
}
document.getElementById("DIV1").style.display = "none";
return true;
The answer is as simple as it is elegant:
var val = document.getElementById("Textbox1").value;
if(!/[^0-9!##$%^&*()+=;./{}|:<>?\[\]\\\'\"]{7}/.test(val)) {
// handle invalid value
}
This tests that the string is 7 characters in length and does not contain any character within the brackets after the "^" (also some characters are escaped with a "\").
You can test in console:
/[^0-9!##$%^&*()+=;./{}|:<>?\[\]\\\'\"]{7}/.test('adfFDKZ'); // returns true
/[^0-9!##$%^&*()+=;./{}|:<>?\[\]\\\'\"]{7}/.test('adf(DKZ'); // returns false
Try this:
/*
* This regex matches all the invalid characters. I escaped the
* special characters.
*/
var regex = /.*[0-9!##\$%\^&\*\(\)\+=\[\]\\';\./\{\}\|":\<\>\?]+.*/;
var text = document.getElementById("TextBox1").value;
/* Test for match...much faster than a for-loop under any circumstances */
if (text.matches(regex)) {
alert("Invalid characters present. Please correct the input");
return false;
}
/* split on delimiter */
var err = $.grep(val.split(','), function(a) { return a.length != 7; });
if (err.length) {
alert("All entries must be seven (7) characters in length. Please correct the following entries: \n" + err);
return false;
}
Please tell me if there are any bugs in this. Also, the only real way to test for this in one step is to set up an enormously long regex. Also, with only one check, it would make it a little harder to guide the user to make the right correction. I will mention that.
I have a script that I'm trying to get working. Basically, what I'm trying to do is prevent someone from entering in special characters in to a field.
the function I have is as follows:
var iChars = "!##$%^&*()+=[];,./{}|<>?;";
if (field1.value.indexOf(iChars) !=-1)
{
alert ("problem")
}
The issue I'm having is that the field is searching for the exact match to the iChars var instead of matching any single value. For example if I create a var test ="one" and enter "one" into the field, it returns with the error, but if I enter "o" into the field, it does not return anything and just passes through to the next portion of the script - but if i entered "none" or "oneeee" it would push the error through.
Any help on fixing this? I tried looking into arrays for indexOf but didn't really understand it, so if you are going to suggest it can you please explain in as much detail as possible.
Thanks
You could use...
var value = field1.value;
for (var i = 0, length = value.length; i < length; i++) {
if (iChars.indexOf(value.charAt(i)) != -1) {
alert('Problem!');
break;
}
}
The problem is you are looking for the index of the entire iChars string in the user input. What you actually want to do though is see if any char in iChars is in the input string. To do this use a for loop
var iChars = "!##$%^&*()+=[];,./{}|<>?;";
var i;
for (i = 0; i < iChars.length; i++) {
if (field1.value.indexOf(iChars[i]) !== -1) {
alert("problem");
break;
}
}
You can also just check against a regular expression:
var iChars = /[!##$%^&*()+=[\];,./{}|<>?;]/;
if (iChars.test(field1.value)) {
alert("problem");
}
This route should be a little more efficient than iterating over each character in the string yourself, and to the regex-trained eye (or at least in my obviously-biased opinion) is simpler to read.