Checking for numbers and dashes - javascript

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.

Related

Test fails when using shorthand operator to determine true or false

I have this unit test which is working fine if I literally return true or false but does not work if I use a shorthand to determine if it is true or false.
Suppose I have this function isMatched where I take in a value to check it with a regex to determine if it matches or not and if it does, then return true, else return false.
function isMatched(value) {
const regex = /^[a-zA-Z0-9 ]*$/;
if (!value || !value.match(regex)){
return false;
}
return true;
}
So I'm testing this function with this test spec:
it('should return true with correct value', () => {
const matched = isMatched('bOomBoom 1');
console.log(matched); // returns true
expect(matched).toBe(true);
});
This passes the test perfectly but if I remove the if block from isMatched function and replace it with return value && value.match(regex), then the test fails and the log shows an array of value, index, input and groups.
What is this sorcery?
Logical AND (&&) evaluates operands from left to right, returning immediately with the value of the first falsy operand it encounters; if all values are truthy, the value of the last operand is returned.
MDN
The expression
value && value.match(regex)
has two possible outputs:
value is truthy -> return value.match(regex)
value is falsy -> return value
You have to convert the result to a boolean for your test. One way is to negate the result twice:
!!(value && value.match(regex))

How to remove a part of a string which will always be at the last?

I made a function that removes the last part of the string which will always start from _ and get the integer, but all I get is the text part and not the integer
How can this be achieved?
function splitLast(arg) {
if (arg.includes(".") && arg.includes("_")) {
return parseFloat(arg.split("_").pop())
} else if (arg.includes(".") != true && arg.includes("_")) {
return parseInt(+arg.split("_").pop())
} else {
throw "Arguments passed does not contain the valid result characters or isnt a required Datatype for thefunction"
}
}
console.log(splitLast("22_no"), 'should be 22')
console.log(splitLast("22.1_no"), 'should be 22.1')
UPD: A better solution
You can use parseFloat() function without additional checks and string parsing (it will do it all for you):
function splitLast(arg) {
if (isNaN(arg.trim()[0])) {
throw new Error('argument is not valid')
}
return parseFloat(arg)
}
console.log(splitLast("22_no"), 'should be 22')
console.log(splitLast("22.1_no"), 'should be 22.1')
console.log(splitLast("a22.1_no"), 'should throw')
console.log(splitLast(" a22.1_no"), 'should throw')
isNaN() check is needed because parseFloat(string) returns:
A floating-point number parsed from the given string (which is exactly what you need)
NaN when the first non-whitespace character cannot be converted to a number (which is an edge-case but we should know about it)
Old solution:
Probably, you have to use the shift() method instead of pop().
The pop() method removes the last element from an array and returns that element. This method changes the length of the array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop
The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
function splitLast(arg) {
if (arg.includes(".") && arg.includes("_")) {
return parseFloat(arg.split("_").shift())
} else if (arg.includes(".") != true && arg.includes("_")) {
return parseInt(arg.split("_").shift())
} else {
throw "Arguments passed does not contain the valid result characters or isnt a required Datatype for thefunction"
}
}
console.log(splitLast("22_no"), 'should be 22')
console.log(splitLast("22.1_no"), 'should be 22.1')
You could use a regexp and .replace:
function splitLast(value) {
return value.replace(/_.*$/, '');
}
console.log(splitLast("22_no"), 'should be 22')
console.log(splitLast("22.1_no"), 'should be 22.1')
You can use this to remove text from string and only numbers with underscore remains.
var ret = "22.1_no";
var str = ret.replace(/[^0-9\.]+/g, "");
console.log("_"+str);

How to check weather the Variable includes number alphabet or character in JavaScript

I want to write a program in JavaScript for password strength calculator so i need 3 function.
One function tells whether the varaible passed has Alphabet or not and same check for Numeric and Characters
var = 'abc123'
function alpha(var) {
// Should return true if variable includes alphabet and false if not
}
function Num(var) {
// Should return true if variable includes Numeric value and false if not
}
function SpecialChar(var) {
// Should return true if variable includes any Special Character and false if not
}
I have tried this method
var password = 'abc123'
function alpha() {
return password.match(/^[a-zA-Z- ]+$/) ? true : false
}
function num() {
return password.match(/^[0-9]+$/)
}
but this not works as i want
Instead of match i suggest using test it will return true or false based on the given expression.
Second of all you are using ^ and $ which mean the start and end of the string. If you remove them your regex works. The reason we don't need them is because right now you're saying "I need atleast one alphanumeric character between the start and the end of the string, nothing else". Same goes for the second function but then with numbers instead of alphanumeric characters
var password = 'abc123'
function hasAlpha(str){
return /[a-zA-Z- ]+/.test(str);
}
function hasNum(str){
return /[0-9]+/.test(str);
}
console.log(hasAlpha(password));
console.log(hasNum(password));
what if you try following regex instead ?
/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##\$%\^&\*])(?=.{8,})/
this will match for password strength which i guess you are looking for.

Finding variable types from a string

Pardon if this question has already been answered however I'm struggling to find the any answers to it.
I'm looking to see if I can convert variable types to a string in the code below.
input = prompt('Type something please', 'your input here')
alert(input + ' is a ' + typeof input)
i.e. if the user were to type 1 typeof would return number, or if the user were to enter true it would return a boolean
You can run the input through a series of parseInt, parseFloat and
parseBool
functions.
Whenever you get a valid result, return it.
Something similar to:
if (parseInt(input) != NaN) {
return "int"
}
if (parseFloat(input) != NaN) {
return "float"
}
Generally, all inputs per your example will return a string careless of what they entered or intended to enter. We could however build a few logics to check if what they entered is; Strings (Alphabets only) or an integer (numbers only) or any other ones per a few other logics you could base your checks on.
One of the quickest ways to check if an input contains a number or not;
isNaN(input) // this returns true if the variable does NOT contain a valid number
eg.
isNaN(123) // false
isNaN('123') // false
isNaN('1e10000') // false (This translates to Infinity, which is a number)
isNaN('foo') // true
isNaN('10px') // true
you could try regex (which is not always ideal but works)
var input = "123";
if(num.match(/^-{0,1}\d+$/)){
//return true if positive or negative
}else if(num.match(/^\d+\.\d+$/)){
//return true if float
}else{
// return false neither worked
}
You could also use the (typeof input) but this will be more convenient if your user is going to enter an expected set of entries
var input = true;
alert(typeof input);
// This eg will return bolean
Let me know if this helps.

Javascript - check if string can be converted to integer?

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

Categories

Resources