How to check condition in JavaScript with ASCII value? - javascript

I'm trying to do a validation for the input field and wanted to check if it's a special character or not
so I though I can check that with ASCII value but not sure how is that done in JavaScript language.
In C I can just check with the string of array right away.
if (input < 4 && document.myTable.inputField.value[0] < 65 )
I want to check if it's they have less than four character and those are special characters if yes I will give them an error message else just do nothing.

In C, brute force checking is the cleanest and easiest alternative. In JavaScript, it is not.
js> /^[A-Za-z]+$/.test('foo')
true
js> /^[A-Za-z]+$/.test('bar123')
false

You can use regular expressions. I think that's easier to read. For example: (/a-z/gi).test(myString) returns true if myString contains anything except letters (upper or lower case). So your condition can be changed to:
if (input < 4 && !(/a-z/gi).test(document.myTable.inputField.value))

You can use the charCodeAt method of String to determine the ASCII code at a certain position. Assuming that by input you mean the input field, this would be a way to do it:
var input = document.myTable.inputField.value;
if (input.length < 4 && input.charCodeAt(0) < 65 ) { /* etc. */ }
// examples charCodeAt
'foo'.charCodeAt(0); //=> 102
'-foo'.charCodeAt(0); //=> 45

Related

Using typeof operator in JS correctly?

I am making a simple hangman game in JavaScript. I'm playing around trying to add new features and one of the features I'd like to add is to check the input the user gives (when they guess a letter of the unknown word) to make sure it is in fact an alphanumeric input (or my intention is to check that the input isn't a symbol like "!" or a number like "5").
I know I could probably use a global variable that contains all the valid characters and check the input against those characters but I was wondering if there is a built in method for this. I found the typeof operator but it seems that the types of characters I'm checking for get converted to strings by JavaScript.
The loop in which I'm trying to implement this:
while (remainingLetters > 0 && numberOfGuesses > 0) {
alert(answerArray.join(" "));
alert("You have " + numberOfGuesses + " guesses remaining.");
var guess = prompt("Guess a letter, or click \
'Cancel' to stop playing.").toLowerCase();
if (guess === null) {
break;
} else if (typeof guess === "number") {
alert("Please enter a single LETTER.");
} else if (guess.length !== 1) {
alert("Please enter a single letter.");
} else {
for (var j = 0; j < word.length; j++) {
if (word[j] === guess) {
answerArray[j] = guess;
remainingLetters--;
// there is some code missing here that I'm pretty sure is not essential
// to my question!
When I run that in Chrome's dev tools, I can input "2" and it never gives me the alert I'm looking for - it doesn't crash or anything it just re-starts the loop (which is the status quo before I tried to implement this "feature").
Thanks in advance!
The issue with this code is that prompt always returns a string value. These values may or may not be able to be converted to a Number; this conversion would be performed using parseInt or parseFloat. (If the string can be converted to a numerical value, these methods return that value; otherwise, they return NaN.) However, typeof performs no interpolation—it states the type of the variable as it exists, and not any types to which it could potentially be converted. Therefore, typeof guess will always evaluate to string. To check if a string contains a numerical value, you could use the condition if (!isNaN(parseInt(guess)) or if (!isNaN(parseFloat(guess)) (note that the isNaN method must be used instead of a traditional equality check).
However, you might want to structure your checks around ensuring that the entry is a letter rather than accounting for the myriad ways in which it might not be. For instance, # and ≥ are not numbers, but they are also not letters. Similarly, if your answerArray contains only Latin letters without diacritics, you might want to disallow guesses of characters like é and ç. Thus, consider using RegEx to check if the guessed string contains an acceptable letter. As in this Stack Overflow post, you can use the following if statement to ensure that the string is one character long and is a valid letter: if (str.length === 1 && str.match(/[a-z]/)). You can refer to that post for ways of addressing more complicated character sets (e.g., non-Latin letters or those with diacritics).

Calculate real length of a string, like we do with the caret

What I want is to calculate how much time the caret will move from the beginning till the end of the string.
Explanations:
Look this string "" in this fiddle: http://jsfiddle.net/RFuQ3/
If you put the caret before the first quote then push the right arrow ► you will push 3 times to arrive after the second quote (instead of 2 times for an empty string).
The first way, and the easiest to calculate the length of a string is <string>.length.
But here, it returns 2.
The second way, from JavaScript Get real length of a string (without entities) gives 2 too.
How can I get 1?
1-I thought to a way to put the string in a text input, and then do a while loop with a try{setCaret}catch(){}
2-It's just for fun
The character in your question "󠀁" is the
Unicode Character 'LANGUAGE TAG' (U+E0001).
From the following Stack Overflow questions,
" Expressing UTF-16 unicode characters in JavaScript"
" How can I tell if a string contains multibyte characters in Javascript?"
we learn that
JavaScript strings are UCS-2 encoded but can represent Unicode code points outside the Basic Multilingual Pane (U+0000-U+D7FF and U+E000-U+FFFF) using two 16 bit numbers (a UTF-16 surrogate pair), the first of which must be in the range U+D800-U+DFFF.
The UTF-16 surrogate pair representing "󠀁" is U+DB40 and U+DC01. In decimal U+DB40 is 56128, and U+DC01 is 56321.
console.log("󠀁".length); // 2
console.log("󠀁".charCodeAt(0)); // 56128
console.log("󠀁".charCodeAt(1)); // 56321
console.log("\uDB40\uDC01" === "󠀁"); // true
console.log(String.fromCharCode(0xDB40, 0xDC01) === "󠀁"); // true
Adapting the code from https://stackoverflow.com/a/4885062/788324, we just need to count the number of code points to arrive at the correct answer:
var getNumCodePoints = function(str) {
var numCodePoints = 0;
for (var i = 0; i < str.length; i++) {
var charCode = str.charCodeAt(i);
if ((charCode & 0xF800) == 0xD800) {
i++;
}
numCodePoints++;
}
return numCodePoints;
};
console.log(getNumCodePoints("󠀁")); // 1
jsFiddle Demo
function realLength(str) {
var i = 1;
while (str.substring(i,i+1) != "") i++;
return (i-1);
}
Didn't try the code, but it should work I think.
Javascript doesn't really support unicode.
You can try
yourstring.replace(/[\uD800-\uDFFF]{2}/g, "0").length
for what it's worth

JavaScript variable less than 4 characters

I have "name" JavaScript variable. If variable "name" contains less than 4 characters I want to execute line: msg('name','Your name must contain minimum 4 characters.')';
I have tried something like this but it interpretated mathematical. Any idea? Thank you.
if(name < 4 ) {
msg('name','Your name must contain minimum 4 characters.');
return false;
}
if (name.length < 4) {
...
}
You probably want to check the length of the string, not the numeric value of the string itself:
if(name.length < 4) {
// ...
if(name.length < 4) {
//Do something
}
You have to check the length of the variable.
length can also be used to check the length of an Array
\n (new line) is also counted as a character.
Depending on your definition of “character”, all answers posted so far are incorrect. The string.length answer is only reliable when you’re certain that only BMP Unicode symbols will be entered. For example, 'a'.length == 1, as you’d expect.
However, for supplementary (non-BMP) symbols, things are a bit different. For example, '𝌆'.length == 2, even though there’s only one Unicode symbol there. This is because JavaScript exposes UCS-2 code units as “characters”.
Luckily, it’s still possible to count the number of Unicode symbols in a JavaScript string through some hackery. You could use Punycode.js’s utility functions to convert between UCS-2 strings and UTF-16 code points for this:
// `String.length` replacement that only counts full Unicode characters
punycode.ucs2.decode('a').length; // 1
punycode.ucs2.decode('𝌆').length; // 1 (note that `'𝌆'.length == 2`!)

JavaScript Number preserve leading 0

I have a problem, I build a very simple javascript search for postal codes.
I am using JS Numbers because I want to check if the passed number (search term) is less||equal or more||equal to the max and min.
value >= splitZips[0] && value <= splitZips[1]
But the Javascript Number var type deletes leading 0, which is a problem because I have postal codes like 01075 and also postal codes like 8430. So it can not find the small 4 digit codes.
Any idea how to fix this?
Represent them as a String. Outside of strict mode, a leading zero denotes an octal number otherwise.
Also, why would a leading zero have any significance when calculating numbers? Just use parseInt(num, 10) if you need to.
Store and display the postcodes as strings, thus retaining the leading zeros. If you need to make a numerical comparison convert to number at the time. The easiest way to convert is with the unary plus operator:
var strPC = "01745",
numPC = +strPC;
alert(numPC === +"01745"); // true
+value >= +splitZips[0] && +value <= +splitZips[1];
// etc.
Before you start comparing you might want to ensure the entered value actually is numeric - an easy way to be sure it is a four or five digit code with or without leading zeros is with a regex:
/^\d{4,5}$/.test(searchTerm) // returns true or false
Instead a parseInt you could use type casting :)
"0123">"122" // false
+"0123">"122" // true | that means: 123>"122"
Btw, what more you can use a each of bitwise operators :
~~"0123"
"0123"|0
"0123"&"0123"
"0123">>0
"0123"<<0
With the same effect :)

Check string for integer

I want to validate a input field. The user should type in a phone number with minimum length of 10 digits.
So I need to check for illegal chars. It would be nice just to check wheather the input is an integer or not.
I came up with this but it does not work (n would be the string).
function isInt(n){
return typeof n== 'number' && n%1==0;
}
Any ideas?
You can do a test like this:
input.length >= 10 && /^[0-9]+$/.test(input)
That will fail if there are non-digits in the string or the string is less than 10 chars long
This should work((input - 0) automatically tries to convert the value to a number):
function isInt(input){
return ((input - 0) == input && input % 1==0);
}
There is already an SO-question about this issue: Validate decimal numbers in JavaScript - IsNumeric()
Might be an overkill for you, but Google has not too long ago announced a library for phone validation. Java and Javascript variants are available.
Validating a phone number is a little more complicated than checking if the input is an integer. As an example phone numbers can and do begin with zeros so it isn't technically and int. Also users may enter dashes: For example:
00 34 922-123-456
So, as for validating it you have a couple of options:
Use regex expression to validate, have a look at:
http://regexlib.com/
this site will have hundreds of examples
Use looping to check each characters in turn, i.e. is character int or dash
I would recommend the former as the latter depends on consistent input from users and you aren't going to get that
Why not use:
return (+val === ~~val && null !== val);
as a return in your function?
this is the output of the javascript console
> +"foobar" === ~~"foobar"
false
> +1.6 === ~~1.6
false
> +'-1' === ~~'-1'
true
> +'-1.56' === ~~'-1.56'
false
> +1 === ~~1
true
> +-1 === ~~-1
true
> +null === ~~null // this is why we need the "&& null !== val" in our return call
true

Categories

Resources