How can I simply check if string can be converted to integer?
And I mean only integer, so string like '10.1' would not be converted to 10.
For example if I do:
parseInt('10.1', 10)
It returns 10
Is there something equivalent like it is in Python, so I would not need to do lots of checks?
In Python if I do int('10.1'), it gives me error, but if string is actually integer, only then it lets you convert it like int('10'). So it is very easy to check that without even using regex or some additional checks.
I tried this:
function isInteger (value) {
if ($.isNumeric(value) && Number(value) % 1 === 0){
return true;
} else {
return false;
}
}
It kinda works, but if I write for example 10., it will return true, because Number converts to 10. I guess I need to use regex to check such thing?
P.S. I searched for this question, but all answers seem to be vague and actually does not answer how to properly check for integer (not just if it is number).
One possibility is to use a regex to test, like so:
function isInteger(value) {
return /^\d+$/.test(value);
}
If i understand your question correctly then this should do it:
function isInteger(value) {
if(parseInt(value,10).toString()===value) {
return true
}
return false;
}
It converts a string to an integer and then back to a string and compares that to the original string. If they match, then it returns true, else it returns false.
You can use
Number function of js (http://www.w3schools.com/jsref/jsref_number.asp)
or
parseInt function of js (http://www.w3schools.com/jsref/jsref_parseint.asp)
You can use regex to detect if it match any value.
function isInterger(value) {
if (value.match(/^\d+$/) {
return true;
} else {
return false;
}
}
https://regex101.com/r/lE5tK1/1
Related
First, I'm sorry I can't speak English well.
I have some problems studying JS. I want to return true if the string is a Number.
If string is "0x10", "0b10", "9843" it work well (all return true).
And string like "a463" return false well.
But, when the string is a string with an exponent like "1e43"... it doesn't work well. (it's return false)
I want to return true when string with exponent.
if (isNaN(s - 0)) {
return false;
} else {
return true;
}
I think have a problem with if().
So, How can I get return true, when the string is with exponent, like "1e22", "13e7"?
I've been working on learning JS, and I can't seem to figure out why my boolean values keep coming back either always true or always false.
So I believe I understand the basics of the truthy/falsy situation in JS, but I can't seem to get it right. I know that there are data type issues, (can't make different data types do different things).
function lastCharacter(char1, char2) {
if (char1[-1] === '' && char2[-1] === '') {
return true;
} else {
return false;
}
}
console.log(lastCharacter('apple', 'pumpkine'));
Or
function lastCharacter(char1, char2) {
if (char1[-1] === char2[-1]) {
return true;
} else {
return false;
}
}
console.log(lastCharacter('apple', 'pumpkina'));
Define a function lastCharacter that accepts two strings as arguments.
lastCharacter should return true if both strings end with the same character.
Otherwise, lastCharacter should return false.
They either return always true or always false. Can anyone help me?
You need a different method for getting the last character of a string, preferably with String#slice and a negative value for getting the last one. Then compare and return the result.
function lastCharacter(string1, string2) {
return string1.slice(-1) === string2.slice(-1);
}
console.log(lastCharacter('apple', 'pumpkine'));
A comparison between taking the last character of an empty string by using an index -1 which returns undefined and slice, which returns an empty string.
var x = '';
console.log('#' + x.slice(-1) + '#');
console.log('#' + x[x.length -1] + '#');
You can use slice
function lastCharacter(char1, char2) {
return char1.slice(-1) === char2.slice(-1)
}
console.log(lastCharacter('apple', 'pumpkina'));
console.log(lastCharacter('apple', 'snake'));
Or you can just access the last index
function lastCharacter(char1, char2) {
return char1[char1.length-1] === char2[char2.length-1]
}
console.log(lastCharacter('apple', 'pumpkina'));
console.log(lastCharacter('apple', 'snake'));
There are no negative array indexes in JavaScript, instead of char1[-1] you have to use char1[char1.length - 1].
Accessing one of a strings characters (e.g. "abc[1]) will always have a length of 1, it will never be equal to "". Your second function makes more sense.
Also
if(condition) { return true; } else { return false; }
is equal to
return condition;
The notation [-1] does not implicitly mean "one character from the end of the string" in JavaScript. You can use str[str.length - 1]. (If you expect possible empty source strings, you'd want to check for that too to avoid ending up with exactly the same problem.)
Instead of an if/else that returns either true or false, just return the results of the logical expression:
return char1[char1.length - 1] === '' && char2[char2.length - 1] === '';
Both the === comparisons return either true or false anyway, so the overall expression value has to be one of those. In general however if you want to make absolutely sure that you end up with a boolean, you can prefix an expression with !! to force the standard JavaScript "truthy-falsy" evaluation:
return !!(expression);
Answer #Wiktor Stribiżew suggested:
function myValidate(word) {
return (word.length === 1 || /[^A-Z]/i.test(word)) ? true : false;
}
Hello during the creation of an array I have a function that will not allow words with certain characters etc to be added to the array
function myValidate(word) {
// No one letter words
if (word.length === 1) {
return true;
}
if (word.indexOf('^') > -1 || word.indexOf('$') > -1) {
return true;
}
return false;
}
It seems like not the proper way of going about this and ive been looking into a regex that would handle it but have not been successful implementing it, tried numerous efforts like:
if (word.match('/[^A-Za-z]+/g') ) {
return true;
}
can some one shed some light on the proper way of handling this?
I suggest using a simpler solution:
function myValidate(word) {
return (word.length === 1 || /[^A-Z]/i.test(word)) ? false : true;
}
var words = ["Fat", "Gnat", "x3-2741996", "1996", "user[50]", "definitions(edit)", "synopsis)"];
document.body.innerHTML = JSON.stringify(words.filter(x => myValidate(x)));
Where:
word.length === 1 checks for the string length
/[^A-Z]/i.test(word) checks if there is a non-ASCII-letter symbol in the string
If any of the above condition is met, the word is taken out of the array. The rest remains.
EDIT: using test instead of match
You want to use test() because it returns a bool telling you if you match the regex or not. The match(), instead, always returns the matched elements. Those may be cast to true by coercion. This is not what you want.
To sum it all up you can just use this one-liner (no if needed and no quotes either, cannot get any simpler):
return word.test(/^[a-zA-Z][a-zA-Z]+$/); // two letter words
You should whitelist characters instead of blacklisting. That's one of the principles in security. In your case, don't tell what is wrong, but tell what is right:
if (word.test('/^[a-zA-Z]+$/')) { // two letter words
return false;
}
This will return false for all words that contain ONLY [a-zA-Z] characters. I guess this is what you want.
Your regex, instead, looked for illegal characters by negating the character group with the leading ^.
Two recommendations:
Just use regex in a positive way (without negation) and it'll be a lot easier to understand.
Also, validation functions normally return true for good data and false for bad data.
It is more readable this way:
if (validate(data))
{
// that's some good data we have here!
}
I am checking an index Of string in JAVASCRIPT. and this is coming as false. where as the value does belong to it as below :
if(idOfControl.indexOf(idOfButton)) == is giving false for the below values.
idOfControl = "dlInventory_btnEditComment_0"
idOfButton = "dlInventory_btnEditComment"
But if I run idOfControl.replace(idOfButton, ""); It is working and replacing the text.
Any reason for this?
indexOf can also return 0, in the event of your string being found at the position 0. 0 evaluates to false. Try:
if(idOfControl.indexOf(idOfButton) > -1)
More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
There are these three big options:
indexOf > -1
The result of indexOf can be 0 meaning that the string was found at the beginning of the string. When string is not found, the return value is -1, therefore:
if (idOfControl.indexOf(idOfButton) > -1) {
// Do something
}
Which can be nicer written as #paxdiablo commented:
if (idOfControl.indexOf(idOfButton) >= 0) {
// Do something
}
via regex
You can use a very simple regular expression to test your match.
var idOfControl = "dlInventory_btnEditComment_0"
var control = /dlInventory_btnEditComment/;
if (idOfControl.test(control)) {
// do something
}
This approach can be enhanced to capture the last number of your string (if you need it)
var idOfControl = "dlInventory_btnEditComment_0"
var control = /dlInventory_btnEditComment_(\d+)/;
var match = control.exec(idOfControl);
if (match) {
alert('the number found is: ' + match[1]);
}
You can try it out here: http://jsfiddle.net/4Z9UC/
via indexOf in a hacky way
This uses a bitwise operator to return a truthy value when the position is !=-1 (In two's complement notation, -1 is internally represented as 111...111, and its inversion is 000...000 which is 0, i.e. a falsy value). It is in fact more efficient than the >-1 option, but it is harder to read and to understand. (EDIT: this became so popular that you can say it is a standard)
if (~idOfControl.indexOf(idOfButton)) {
// do something
}
I have a check on submit to validate some fields and I need to check for only numbers and dashes:
var numPattern = /^[0-9\-]+$/;
//UI field null check
if (ssn != (numPattern.test(ssn))) {
displayError(Messages.ERR_TOPLEVEL);
}
if (accntNoCL != (numPattern.test(accntNoCL))) {
displayError(Messages.ERR_TOPLEVEL);
}
This is not working for some reason. Any ideas why that is?
The regex.test() function, or numPattern.test() in your case, returns a boolean true/false result.
In your code, if (ssn != numPattern.test(ssn)), you're checking if the result is equal to the value you're testing.
Try changing it to the following:
if (!numPattern.test(ssn)) {
test is a predicate, it returns a boolean:
var numPattern = /^[0-9\-]+$/;
numPattern.test("hello, world!"); // false
numPattern.test("123abc"); // false
numPattern.test("123"); // true
numPattern.test("12-3"); // true
test returns a boolean, not a match. Simply use
if (!numPattern.test(ssn)) {
displayError(Messages.ERR_TOPLEVEL);
}
if (!numPattern.test(accntNoCL)) {
displayError(Messages.ERR_TOPLEVEL);
}
If you ever need a match, use either the match function of strings or the exec function of regex objects.