Best way to check if a number contains another number - javascript

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. :)

Related

Get substings between Specific Characters

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.

Highest power of two - javascript

I'm using google apps scripts, that works with javascript and I'm writing a piece of code that returns the highest power of two that divides a number, but it doesn't work. Why??
function HP2(input) {
var i = 1;
while(input % 2^i = 0){
i++;
};
return 2^i;
}
Thanks!!
You need to use == in the while condition and the Math.pow function instead of the xor operator ^. Also the return should be i-1.
function HP2(input) {
var i = 1;
while(input % Math.pow(2, i) == 0) {
i++;
};
return Math.pow(2, i-1);
}
if you stay in the 32-bit range (at least for the divisor) this would be way more performant way:
function HP2(input){
for(var i=0; i<31 && !(input & (1<<i)); ++i);
return (1<<i)>>>0;
}

JavaScript REGEX - Identical number 3 times in any order

Trying to catch any occurance of the same number of a value. Can match the same number (x)times if they are in sequence with
((?:1){3}|(?:2){3}|(?:3){3}|(?:4){3}|(?:5){3}|(?:6){3}|(?:7){3}|(?:8){3}|(?:9){3|(?:0){3})
But need to also catch if the same number exists 3 times in the entire value. So
1110 //true
1123 //false
1121 //true
3212 //false
You can use a regex like this:
(\d)\d*\1\d*\1
Working demo
Update: as zzzzBox pointed in this comment
(?:(\d)[\s\S]*)(?:\1[\s\S]*){2}
..if you want any character between numbers
You can use "1110".match(/1/g).length >= 3:
function number_exists_3_times(input) {
var result = false, matches;
for (i = 0; i <= 9 && result === false; i += 1) {
matches = input.match(new RegExp("" + i, "g"));
result = (matches !== null && matches.length >= 3);
}
return result;
}
console.log(number_exists_3_times("1110")); // true
console.log(number_exists_3_times("1123")); // false
console.log(number_exists_3_times("1121")); // true
console.log(number_exists_3_times("3212")); // false

If number ends with 1 do something

I want to make something like this:
if(day==1 || day==11 || day==21 || day==31 || day==41 ......){
result="dan";
}
else{
result="dana";
}
How can i do that with every number that ends with one and of course without writing all numbers?
Just check the remainder of division by 10:
if (day % 10 == 1) {
result = "dan";
} else {
result = "dana";
}
% is the "Modulo" or "Modulus" Operator, unless you're using JavaScript, in which case it is a simple remainder operator (not a true modulo). It divides the two numbers, and returns the remainder.
You can check the remainder of a division by 10 using the Modulus operator.
if (day % 10 == 1)
{
result = "dan";
}
else
{
result = "dana";
}
Or if you want to avoid a normal if:
result = "dan" + (day % 10 == 1 ? "" : "a");
% is the Javascript Modulus operator. It gives you the remainder of a division:
Example:
11 / 10 = 1 with remainder 1.
21 / 10 = 2 with remainder 1.
31 / 10 = 3 with remainder 1.
...
See this answer: What does % do in JavaScript? for a detailed explication of what the operator does.
Modulus operator. You can research it but basically you want to detect if a number when divided by 10 has a remainder of 1:
if( day%10 == 1)
this can be solved by single line
return (day % 10 == 1) ? 'dan' : 'dana';
You can convert the number to a string and use String.prototype.endsWith().
const number = 151
const isMatch = number.toString().endsWith('1')
let result = ''
if (isMatch) {
result = 'dan'
} else {
result = 'dana'
}
I'm using it in some code that sets the ordinal. For example, if you want to display 1st, 2nd, 3rd, or 4th:
let ordinal = 'th';
if (number.toString().endsWith('1')) {
ordinal = 'st'
}
if (number.toString().endsWith('2')) {
ordinal = 'nd'
}
if (number.toString().endsWith('3')) {
ordinal = 'rd'
}

How to check if a string is a natural number?

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.

Categories