In javascript, how can you check if a string is a natural number (including zeros)?
Thanks
Examples:
'0' // ok
'1' // ok
'-1' // not ok
'-1.1' // not ok
'1.1' // not ok
'abc' // not ok
Here is my solution:
function isNaturalNumber(n) {
n = n.toString(); // force the value incase it is not
var n1 = Math.abs(n),
n2 = parseInt(n, 10);
return !isNaN(n1) && n2 === n1 && n1.toString() === n;
}
Here is the demo:
var tests = [
'0',
'1',
'-1',
'-1.1',
'1.1',
'12abc123',
'+42',
'0xFF',
'5e3'
];
function isNaturalNumber(n) {
n = n.toString(); // force the value incase it is not
var n1 = Math.abs(n),
n2 = parseInt(n, 10);
return !isNaN(n1) && n2 === n1 && n1.toString() === n;
}
console.log(tests.map(isNaturalNumber));
here is the output:
[true, true, false, false, false, false, false, false, false]
DEMO: http://jsfiddle.net/rlemon/zN6j3/1
Note: this is not a true natural number, however I understood it that the OP did not want a real natural number. Here is the solution for real natural numbers:
function nat(n) {
return n >= 0 && Math.floor(n) === +n;
}
http://jsfiddle.net/KJcKJ/
provided by #BenjaminGruenbaum
Use a regular expression
function isNaturalNumber (str) {
var pattern = /^(0|([1-9]\d*))$/;
return pattern.test(str);
}
The function will return either true or false so you can do a check based on that.
if(isNaturalNumber(number)){
// Do something if the number is natural
}else{
// Do something if it's not natural
}
Source: http://www.codingforums.com/showthread.php?t=148668
If you have a regex phobia, you could do something like this:
function is_natural(s) {
var n = parseInt(s, 10);
return n >= 0 && n.toString() === s;
}
And some tests:
> is_natural('2')
true
> is_natural('2x')
false
> is_natural('2.0')
false
> is_natural('NaN')
false
> is_natural('0')
true
> is_natural(' 2')
false
You can do if(num.match(/^\d+$/)){ alert(num) }
You could use
var inN = !!(+v === Math.abs(~~v) && v.length);
The last test ensures '' gives false.
Note that it wouldn't work with very big numbers (like 1e14)
You can check for int with regexp:
var intRegex = /^\d+$/;
if(intRegex.test(someNumber)) {
alert('Natural');
}
function isNatural(num){
var intNum = parseInt(num);
var floatNum = parseFloat(num);
return (intNum == floatNum) && intNum >=0;
}
Number() parses string input accurately. ("12basdf" is NaN, "+42" is 42, etc.). Use that to check and see if it's a number at all. From there, just do a couple checks to make sure that the input meets the rest of your criteria.
function isNatural(n) {
if(/\./.test(n)) return false; //delete this line if you want n.0 to be true
var num = Number(n);
if(!num && num !== 0) return false;
if(num < 0) return false;
if(num != parseInt(num)) return false; //checks for any decimal digits
return true;
}
function isNatural(n){
return Math.abs(parseInt(+n)) -n === 0;
}
This returns false for '1 dog', '-1', '' or '1.1', and returns true
for non-negative integers or their strings, including '1.2345e12',
and not '1.2345e3'.
I know this thread is a bit old but I believe I've found the most accurate solution thus far:
function isNat(n) { // A natural number is...
return n != null // ...a defined value,
&& n >= 0 // ...nonnegative,
&& n != Infinity // ...finite,
&& typeof n !== 'boolean' // ...not a boolean,
&& !(n instanceof Array) // ...not an array,
&& !(n instanceof Date) // ...not a date,
&& Math.floor(n) === +n; // ...and whole.
}
My solution is basically an evolution of the contribution made by #BenjaminGruenbaum.
To back up my claim of accuracy I've greatly expanded upon the tests that #rlemon made and put every proposed solution including my own through them:
http://jsfiddle.net/icylace/qY3FS/1/
As expected some solutions are more accurate than others but mine is the only one that passes all the tests.
EDIT: I updated isNat() to rely less on duck typing and thus should be even more reliable.
This is how I check if a string is a natural number (including zeros!).
var str = '0' // ok
var str1 = '1' // ok
var str2 = '-1' // not ok
var str3 = '-1.1' // not ok
var str4 = '1.1' // not ok
var str5 = 'abc' // not ok
console.log("is str natural number (including zeros): ", Number.isInteger(Number(str)) && Number(str) >= 0)
console.log("is str1 natural number (including zeros): ", Number.isInteger(Number(str1)) && Number(str1) >= 0)
console.log("is str2 natural number (including zeros): ", Number.isInteger(Number(str2)) && Number(str2) >= 0)
console.log("is str3 natural number (including zeros): ", Number.isInteger(Number(str3)) && Number(str3) >= 0)
console.log("is str4 natural number (including zeros): ", Number.isInteger(Number(str4)) && Number(str4) >= 0)
console.log("is str5 natural number (including zeros): ", Number.isInteger(Number(str5)) && Number(str5) >= 0)
const func = (number) => {
return Math.floor(number) === number
}
Convert the string to a number and then check:
function isNatural( s ) {
var n = +s;
return !isNaN(n) && n >= 0 && n === Math.floor(n);
}
function isNatural(number){
var regex=/^\d*$/;
return regex.test( number );
}
function isNatural(n) {
return Number(n) >= 0 && Number(n) % 1 === 0;
}
Why not simply use modulo?
if(num % 1 !== 0) return false;
Use /^\d+$/ will match 000.
so use /^[1-9]\d*$|^0$/ match positive integer or 0 will be right.
Related
I was only allowed to use google document for writing.
Could you please tell me what I did wrong? The recruiter wont get back to me when I asked her why I failed
Task 1:
Implement function verify(text) which verifies whether parentheses within text are
correctly nested. You need to consider three kinds: (), [], <> and only these kinds.
My Answer:
const verify = (text) => {
const parenthesesStack = [];
for( let i = 0; i<text.length; i++ ) {
const closingParentheses = parenthesesStack[parenthesesStack.length - 1]
if(text[i] === “(” || text[i] === “[” || text[i] === “<” ) {
parenthesisStack.push(text[i]);
} else if ((closingParentheses === “(” && text[i] === “)”) || (closingParentheses === “[” && text[i] === “]”) || (closingParentheses === “<” && text[i] === “>”) ) {
parenthesisStack.pop();
}
};
return parenthesesStack.length ? 0 : 1;
}
Task 2:
Simplify the implementation below as much as you can.
Even better if you can also improve performance as part of the simplification!
FYI: This code is over 35 lines and over 300 tokens, but it can be written in
5 lines and in less than 60 tokens.
Function on the next page.
// ‘a’ and ‘b’ are single character strings
function func2(s, a, b) {
var match_empty=/^$/ ;
if (s.match(match_empty)) {
return -1;
}
var i=s.length-1;
var aIndex=-1;
var bIndex=-1;
while ((aIndex==-1) && (bIndex==-1) && (i>=0)) {
if (s.substring(i, i+1) == a)
aIndex=i;
if (s.substring(i, i+1) == b)
bIndex=i;
i--;
}
if (aIndex != -1) {
if (bIndex == -1)
return aIndex;
return Math.max(aIndex, bIndex);
} else {
if (bIndex != -1)
return bIndex;
return -1;
}
};
My Answer:
const funcSimplified = (s,a,b) => {
if(s.match(/^$/)) {
return -1;
} else {
return Math.max(s.indexOf(a),s.indexOf(b))
}
}
For starters, I'd be clear about exactly what the recruiter asked. Bold and bullet point it and be explicit.
Secondly, I would have failed you from your first 'for' statement.
See my notes:
// Bonus - add jsdoc description, example, expected variables for added intention.
const verify = (text) => {
// verify what? be specific.
const parenthesesStack = [];
for( let i = 0; i<text.length; i++ ) {
// this could have been a map method or reduce method depending on what you were getting out of it. Rarely is a for loop like this used now unless you need to break out of it for performance reasons.
const closingParentheses = parenthesesStack[parenthesesStack.length - 1]
// parenthesesStack.length - 1 === -1.
// parenthesesStack[-1] = undefined
if(text[i] === “(” || text[i] === “[” || text[i] === “<” ) {
parenthesisStack.push(text[i]);
// “ will break. Use "
// would have been more performant and maintainable to create a variable like this:
// const textOutput = text[i]
// if (textOutput === "(" || textOutput === "[" || textOutput === "<") {
parenthesisStack.push(textOutput)
} else if ((closingParentheses === “(” && text[i] === “)”) || (closingParentheses === “[” && text[i] === “]”) || (closingParentheses === “<” && text[i] === “>”) ) {
parenthesisStack.pop();
// There is nothing in parenthesisStack to pop
}
};
return parenthesesStack.length ? 0 : 1;
// Will always be 0.
}
Not exactly what the intention of your function or logic is doing, but It would fail based on what I can see.
Test it in a browser or use typescript playground. You can write javascript in there too.
Hard to tell without the recruiter feedback. But i can tell that you missundertood the second function.
func2("mystrs", 's', 'm') // returns 5
funcSimplified("mystrs", 's', 'm') // returns 3
You are returning Math.max(s.indexOf(a),s.indexOf(b)) instead of Math.max(s.lastIndexOf(a), s.lastIndexOf(b))
The original code start at i=len(str) - 1 and decrease up to 0. They are reading the string backward.
A possible implementation could have been
const lastOccurenceOf = (s,a,b) => {
// Check for falsyness (undefined, null, or empty string)
if (!s) return -1;
// ensure -1 value if search term is empty
const lastIndexOfA = a ? s.lastIndexOf(a) : -1
const lastIndexOfB = b ? s.lastIndexOf(b) : -1
return Math.max(lastIndexOfA, lastIndexOfB)
}
or a more concise example, which is arguably worse (because less readable)
const lastOccurenceOf = (s,a,b) => {
const safeStr = s || '';
return Math.max(safeStr.lastIndexOf(a || undefined), safeStr.lastIndexOf(b || undefined))
}
I'm using a || undefined to force a to be undefined if it is an empty string, because:
"canal".lastIndexOf("") = 5
"canal".lastIndexOf(undefined) = -1
original function would have returned -1 if case of an empty a or b
Also, have you ask if you were allowed to use ES6+ syntax ? You've been given a vanilla JS and you implemented the equivalent using ES6+. Some recruiters have vicious POV.
I am trying to solve some JS problem. I want to check if an IP address is a valid one.
So the numbers must be between 0-255.
So what I want to do at this point, is to get an IP ex 192.168.1.1 and get substrings and load them to an array, so I want to create an array that looks like that:
array = ['192' , '168' , '1' , '1'];
I've tried various approaches in my algorithm but can't manage to target dynamically the numbers and split them between every dot.
I've done several tries, and thats the closest I could get.
let str = '192.168.1.1';
isValidIp(str);
function isValidIP(str) {
let array = [];
let substringArray = [];
for (let i=0; i<str.length; i++){
if (str[i] == '.') array.push(i);
}
let counter = 0;
for (let i in array){
substringArray.push(str.substring(counter, array[i]));
counter = array[i];
}
console.log(substringArray);
}
Which returns:
[ '192', '.168', '.1' ]
You can use the split() function of JavaScript which returns an array of every element separated by the digit specified. Or, which I wouldn't recommend, you could use RegEx. Here is an example of both:
function isValidIPwRegEx(str){
if (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(str))
{
return true;
}
return false;
}
function isValidIP(str) {
let array = str.split("."),
isIP = true;
array = array.filter( block => !block.includes("+") && !block.includes("e") );
if(array.length!=4) return false;
array.forEach((number) => {
if ( !(+number >=0 && +number <= 255) ) { //As #p.s.w.g kindly suggested
isIP = false;
}
});
return isIP;
}
//With RegEx
console.log("With RegEx");
console.log(isValidIPwRegEx("192.168.1.1"));
console.log(isValidIPwRegEx("blah.blah.blah.blah")); //As #georg suggested
console.log(isValidIPwRegEx("1e1.2e1.+3e1.+5e1")); //As #georg again suggested to #Nina Scholz
console.log("");
//Without RegEx
console.log("Without RegEx");
console.log(isValidIP("192.168.1.1"));
console.log(isValidIP("blah.blah.blah.blah")); //As #georg suggested
console.log(isValidIP("1e1.2e1.+3e1.+5e1")); //As #georg again suggested to #Nina Scholz
console.log(isValidIP("1e1.2e1.3e1.5e1"));
Use String's split function.
So, something like "192.168.1.1".split(".")
You could split the string and check if the length is four and all values are integers and smaller than 256.
var ip = '192.168.1.1',
values = ip.split('.'),
valid = values.length === 4 && values.every(v => +v >= 0 && +v < 256);
console.log(values);
console.log(valid);
function isValidIP(str) {
let re = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
let m = str.match(re);
return m &&
m[1] >= 0 && m[1] <= 255 &&
m[2] >= 0 && m[2] <= 255 &&
m[3] >= 0 && m[3] <= 255 &&
m[4] >= 0 && m[4] <= 255
;
}
If you wish to be more precise, each digit check can be:
(0|[1-9]\d{0:2})
This prevents extraneous leading 0's.
If you run an explode in PHP with the resulting array length limited, it will append the remainder of the string to the last element. This is how exploding a string should behave, since nowhere in the split am I saying that I want to discard my data, just split it. This is how it works in PHP:
# Name;Date;Quote
$s = 'Mark Twain;1879-11-14;"We haven\'t all had the good fortune to be ladies; we haven\'t all been generals, or poets, or statesmen; but when the toast works down to the babies, we stand on common ground."';
$a = explode(';',$s,3);
var_dump($a);
array(3) {
[0]=>
string(10) "Mark Twain"
[1]=>
string(10) "1879-11-14"
[2]=>
string(177) ""We haven't all had the good fortune to be ladies; we haven't all been generals, or poets, or statesmen; but when the toast works down to the babies, we stand on common ground.""
}
However, if you run the same code in JavaScript:
> var s = 'Mark Twain;1879-11-14;"We haven\'t all had the good fortune to be ladies; we haven\'t all been generals, or poets, or statesmen; but when the toast works down to the babies, we stand on common ground."'
undefined
> var a = s.split(';',3);
undefined
> a
[ 'Mark Twain',
'1879-11-14',
'"We haven\'t all had the good fortune to be ladies' ]
This makes absolutely no sense, because the whole point of splitting a string is to treat the final portion of the string as a literal, instead of delimited. JavaScript's split with a limit is the exact same as:
# In PHP
$a = array_slice(explode(';',$s), 0, 3);
# Or in JavaScript
var a = s.split(';').slice(0, 3);
If the user in JavaScript only wanted to make use of the first two elements in this array, whether the array is split or not doesn't matter. The first two elements will always have the same value no matter what. The only element that changes, is the last element of the split array.
If the native split with limit method in JavaScript can be replicated using a slice, then what value does it provide?
But I digress, what is the most efficient way to replicate the explode functionality in PHP? Removing each element as a substring until the last element is reached, splitting the entire string and then concatenating the remaining elements, getting the location of the n - 1 delimiter and getting a substring of that, or any other solution I haven't thought of?
According documentation the split function accepts two arguments:
string.split(separator, limit)
However this still gives not the result you want because:
The second parameter is an integer that specifies the number of
splits, items after the split limit will not be included in the array
However, I noticed that the ';' in the text has a space behind it. So you could use a regex.
var s = 'Mark Twain;1879-11-14;"We haven\'t all had the good fortune to be ladies; we haven\'t all been generals, or poets, or statesmen; but when the toast works down to the babies, we stand on common ground."'
var a = s.split(/;(?! )/,3)
console.log(a);
The Regex (/;(?! ) splits all ';' except if there is a space behind it.
Hope this helps!
Loctus.io got you covered, they ported php's explode, and a great number of other php functions to javascript
usage:
$s = 'Mark Twain;1879-11-14;"We haven\'t all had the good fortune to be ladies; we haven\'t all been generals, or poets, or statesmen; but when the toast works down to the babies, we stand on common ground."';
"Mark Twain;1879-11-14;"We haven't all had the good fortune to be ladies; we haven't all been generals, or poets, or statesmen; but when the toast works down to the babies, we stand on common ground.""
$a = explode(';',$s,3);
content of $a as reported by Chrome's javascript console:
0: "Mark Twain"
1: "1879-11-14"
2: ""We haven't all had the good fortune to be ladies; we haven't all been generals, or poets, or statesmen; but when the toast works down to the babies, we stand on common ground.""
length: 3
, source: http://locutus.io/php/strings/explode/
function explode (delimiter, string, limit) {
// discuss at: http://locutus.io/php/explode/
// original by: Kevin van Zonneveld (http://kvz.io)
// example 1: explode(' ', 'Kevin van Zonneveld')
// returns 1: [ 'Kevin', 'van', 'Zonneveld' ]
if (arguments.length < 2 ||
typeof delimiter === 'undefined' ||
typeof string === 'undefined') {
return null
}
if (delimiter === '' ||
delimiter === false ||
delimiter === null) {
return false
}
if (typeof delimiter === 'function' ||
typeof delimiter === 'object' ||
typeof string === 'function' ||
typeof string === 'object') {
return {
0: ''
}
}
if (delimiter === true) {
delimiter = '1'
}
// Here we go...
delimiter += ''
string += ''
var s = string.split(delimiter)
if (typeof limit === 'undefined') return s
// Support for limit
if (limit === 0) limit = 1
// Positive limit
if (limit > 0) {
if (limit >= s.length) {
return s
}
return s
.slice(0, limit - 1)
.concat([s.slice(limit - 1)
.join(delimiter)
])
}
// Negative limit
if (-limit >= s.length) {
return []
}
s.splice(s.length + limit)
return s
}
edit: if you for some reason need/want a smaller implementation, here's 1 i made in response to the comments:
function explode(delimiter, string, limit) {
var spl = string.split(delimiter);
if (spl.length <= limit) {
return spl;
}
var ret = [],i=0;
for (; i < limit; ++i) {
ret.push(spl[i]);
}
for (; i < spl.length; ++i) {
ret[limit - 1] += delimiter+spl[i];
}
return ret;
}
Alright, I created 4 alternative versions of the PHP split string algorithm, along with the two provided by #hanshenrik, and did a basic benchmark on them:
function explode1(delimiter, str, limit) {
if (limit == null) {
return s.split(delimiter);
}
var a = [];
var lastIndex = -1;
var index = 0;
for (var i = 0; i < limit; i++) {
index = str.indexOf(delimiter, lastIndex + 1);
if (i == limit - 1) {
a.push(str.substring(lastIndex + 1));
} else {
a.push(str.substring(lastIndex + 1, index));
}
lastIndex = index;
}
return a;
}
function explode2(delimiter, str, limit) {
if (limit == null) {
return s.split(delimiter);
}
var a = str.split(delimiter);
var ret = a.slice(0, limit - 1);
ret.push(a.slice(limit - 1).join(delimiter));
return ret;
}
function explode3(delimiter, str, limit) {
if (limit == null) {
return s.split(delimiter);
}
var a = s.split(delimiter, limit - 1);
var index = 0;
for (var i = 0; i < limit - 1; i++) {
index = s.indexOf(delimiter, index + 1);
}
a.push(str.substring(index + 1));
return a;
}
function explode4(delimiter, str, limit) {
if (limit == null) {
return s.split(delimiter);
}
var a = str.split(delimiter, limit - 1);
a.push(str.substring(a.join(delimiter).length + 1));
return a;
}
function explode5(delimiter, string, limit) {
// discuss at: http://locutus.io/php/explode/
// original by: Kevin van Zonneveld (http://kvz.io)
// example 1: explode(' ', 'Kevin van Zonneveld')
// returns 1: [ 'Kevin', 'van', 'Zonneveld' ]
if (arguments.length < 2 ||
typeof delimiter === 'undefined' ||
typeof string === 'undefined') {
return null
}
if (delimiter === '' ||
delimiter === false ||
delimiter === null) {
return false
}
if (typeof delimiter === 'function' ||
typeof delimiter === 'object' ||
typeof string === 'function' ||
typeof string === 'object') {
return {
0: ''
}
}
if (delimiter === true) {
delimiter = '1'
}
// Here we go...
delimiter += ''
string += ''
var s = string.split(delimiter)
if (typeof limit === 'undefined') return s
// Support for limit
if (limit === 0) limit = 1
// Positive limit
if (limit > 0) {
if (limit >= s.length) {
return s
}
return s
.slice(0, limit - 1)
.concat([s.slice(limit - 1)
.join(delimiter)
])
}
// Negative limit
if (-limit >= s.length) {
return []
}
s.splice(s.length + limit)
return s
}
function explode6(delimiter, string, limit) {
var spl = string.split(delimiter);
if (spl.length <= limit) {
return spl;
}
var ret = [],i=0;
for (; i < limit; ++i) {
ret.push(spl[i]);
}
for (; i < spl.length; ++i) {
ret[limit - 1] += delimiter+spl[i];
}
return ret;
}
var s = 'Mark Twain,1879-11-14,"We haven\'t all had the good fortune to be ladies; we haven\'t all been generals, or poets, or statesmen; but when the toast works down to the babies, we stand on common ground."'
console.log(s);
console.time('explode1');
var a1 = explode1(',', s, 3);
//console.log(a1);
console.timeEnd('explode1');
console.time('explode2');
var a2 = explode2(',', s, 3);
//console.log(a2);
console.timeEnd('explode2');
console.time('explode3');
var a3 = explode3(',', s, 3);
//console.log(a3);
console.timeEnd('explode3');
console.time('explode4');
var a4 = explode4(',', s, 3);
//console.log(a4);
console.timeEnd('explode4');
console.time('explode5');
var a5 = explode5(',', s, 3);
//console.log(a5);
console.timeEnd('explode5');
console.time('explode6');
var a6 = explode6(',', s, 3);
//console.log(a6);
console.timeEnd('explode6');
The two best-performing algorithms was explode4 principally, with explode3 a close second in multiple iterations of the benchmark:
$ node explode1.js && node explode2.js && node explode3.js && node
explode4.js && node explode5.js && node explode6.js
explode1: 0.200ms
explode2: 0.194ms
explode3: 0.147ms
explode4: 0.183ms
explode5: 0.341ms
explode6: 0.162ms
You can run your own benchmarks, but with my tests I can confirm that splitting an array by n - 1 and then getting an index from joining the resulting array is the fastest algorithm matching explode in PHP.
EDIT: It turns out that the garbage collector biased how each successive function was measured, so I split them off into their own individual files and re-ran the benchmarking a few times. It seems explode3 is the best performing, not explode4, but I won't make a decision that I'm not completely sure of.
can you help me to write a function in javascript to Given two strings, find if they are one edit away from each other example :
(pale, ple ) true
(pales, pale ) true
(pale, bale ) true
(pale, bake) false
(face, facts ) false
Can you try this function to check that string only differs by one edit.
function checkDifferntString(str1, str2) {
let diff = 0;
if (str1 === str2) return true; // equal return true
let lengthDiff = Math.abs(str1.length - str2.length)
if (lengthDiff > 1) return false; // checks length diff if > 2 return false
for (let i=0; (i<str1.length || i < str2.length);i++) {
if (diff > 1) return false; // diff greater than 1 return false
if (str1.charAt(i) !== str2.charAt(i)) diff++
}
if (diff <= 1) return true
else return false;
}
console.log(checkDifferntString("pale", "pale")) // true
console.log(checkDifferntString("pale", "pales")) // true
console.log(checkDifferntString("pales", "pale")) // true
console.log(checkDifferntString("pales", "bale")) // false
I hope it helps. Thanks!
Check this out.
I made a simple function that iterates through the given two strings and check if there's more than 1 difference (in terms of characters) between these strings, an optional argument cs to allow case sensitivity, by default it equals to false, so 'a' and 'A' are the same.
function isEditFrom(str1, str2, cs) {
var cs = cs || false, i = 0, diff = 2, len1 = str1.length, len2 = str2.length, l = (len1 > len2) ? len1: len2;
if(len1 !== 0 && len2 !== 0) {
if(cs === false) {
str1 = str1.toLowerCase();
str2 = str2.toLowerCase();
}
for(; i < l; i++) {
if(str1[i] !== str2[i]) {
if(--diff === 0) {
return false;
}
}
}
return true;
} else {
return false;
}
}
and now we call that function:
isEditFrom('Pale', 'bAle'); // returns True
isEditFrom('Pale', 'bAle', true); // returns False as we set the third argument to true enabling case sensitivity, 'a' != 'A'
isEditFrom('face', 'facts'); // returns False
For example if the number 752 contains the number 5? Whats the best way to check? Convert to string or divide into individual digits?
Convert to string and use indexOf
(752+'').indexOf('5') > -1
console.log((752+'').indexOf('5') > -1);
console.log((752+'').indexOf('9') > -1);
Convert to string and use one of these options:
indexOf():
(number + '').indexOf(needle) > -1;
includes():
(number + '').includes(needle);
You can use 3 ways:
Check it by string contains:
var num = 752;
num.toString().indexOf('5') > -1 //return true or false - contains or not
Check by loop
var f = 2;
while(num > 0 ){
if( num % 10 == f){
console.log("true");
break;
}
num = Math.floor(num / 10);
}
Check by regular expressions
num.toString().match(/5/) != null //return true if contains
function checkNumberIfContainsKey(number, key){
while(number > 0){
if(number%10 == key){
return true;
}
number = Math.trunc(number / 10);
}
return false;
}
console.log(
checkNumberIfContainsKey(19, 9), //true
checkNumberIfContainsKey(191, 9), //true
checkNumberIfContainsKey(912, 9), //true
checkNumberIfContainsKey(185, 9) //false
);
The most efficient solution among available answers because of the complexity of this program is just O(number of digits) if number = 10235 then the number of digits = 5
You can also use "some" function.
"Some"thing like this:
function hasFive(num){
return num.toString().split("").some(function(item){
return item === "5";
});
}
and then you can call it:
hasFive(752)
Further improved is that you make a function that takes number and digit you want to check:
function hasNumber(num, digit){
return num.toString().split("").some(function(item){
return item == digit;
});
}
And then call it in similar way:
hasNumber(1234,3) //true
hasNumber(1244,3) //false
So that way we can check any number for any digit.
I hope so "some"one will find this useful. :)