Specify Range of Numbers Javascript in Conditional Statement - javascript

I am sort of new to Javascript Code and I'm wondering how can I specify that x in this case can be a number in between 750 to 850.
else if(DATA == "PULSOUT 12, x") {
*Note DATA is a user input that was taken from a textarea if that info is needed.

#Ahm23, Try this:
if (DATA.substr(0,11) == "PULSOUT 12," && parseInt(DATA.substr(11).trim()) >= 750 && parseInt(DATA.substr(11).trim()) <= 850) {

You can define a function which checks if input is within range 751-849 where array contains elements [750, 850], pass or define array containing ranges at second parameter, use logic n > range[0] && n < range[1], where n is user input. You can use .match(), RegExp /\d+$ to get digits before end of string, `
let x = "750";
function checkX(n, range = [750, 850]) {
return n > range[0] && n < range[1]
}
console.log(checkX(x)); // false
console.log(checkX(x = 751)); // true
console.log(checkX(x = 850)); // false
let DATA = `PULSOUT 12, ${x = 808}`;
console.log(
checkX(x = DATA.match(/\d+$/g).pop())
&& DATA.replace(/\d+$/, "") === "PULSOUT 12, "
); // true

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.

Simple calculator example using array to store input values

The input values are stored in an array, the below loop is to calculate the final result, by looping through the array and appending the operators and numbers to a variable which is then evaluated.
privateCalculate = function () {
var total;
for(i = 0; i < init.sequence.length; i++) {
if(init.sequence[i] === "+" || init.sequence[i] === "-" ||
init.sequence[i] === "*" || init.sequence[i] === "/" ||
init.sequence[i] === "(" || init.sequence[i] === ")")
{
total += init.sequence[i];
} else {
init.sequence[i] = parseFloat(init.sequence[i]);
total += init.sequence[i];
}
}
console.log(eval(total));
//console.log((parseFloat(1)+parseFloat(2))/parseFloat(2));
},
The function produces "NaN"
You said your input is: ["5","+","5"]
You don't need to parse it, because evaltakes as parameter a String
Just do this:
var inputArray = ["5","+","5"];
eval(inputArray.join('')) // -> 10

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.

Format currency using javascript

a script returns either a number like 0.0580 so in x.xxxx format or a (x) for X units left.
I want to format the number 0.0580 and return 5.8 cent or return x units left.
Any ideas how to do that in javascript? Especially how do I format the x.xxxx?
In case the first x is not 0 I want to return e.g. 1.75$.
MS has written a nice plugin for jquery. it's especially useful if you're localizing. Give it a go:
http://weblogs.asp.net/scottgu/archive/2010/06/10/jquery-globalization-plugin-from-microsoft.aspx
I'm not sure if this can be used outside of jquery...
I may be spoiling you here, but whatever. Here's a function that I found somewhere at some point and have been recycling since. I haven't actually bothered to look much into it to figure out what it does exactly, but it has been rather useful:
function FormatMoneyAmount(starting_string, ending_string) {
//check validity of input (true = invalid, false = valid)
var valid_exp = new RegExp ('[^0-9,.$]', 'gi');
input_invalid = (typeof(ending_string) == 'undefined' && valid_exp.test(starting_string));
//check if more than 2 digits follow decimal or no decimal
decimal_invalid = typeof(ending_string) == 'undefined' && (starting_string.indexOf('.') > -1) && ((starting_string.length - starting_string.indexOf('.')) > 3);
if (input_invalid || decimal_invalid) {
ending_string = starting_string;
} else {
//remove commas, dollar signs
var replace_exp = new RegExp ('[,$]', 'gi');
starting_string = starting_string.replace(replace_exp, '');
//remove decimal if ending string not set, save for adding on later
var decimal_substring = '';
if (typeof(ending_string) == 'undefined' && starting_string.indexOf('.') > -1) {
decimal_substring = starting_string.substring(starting_string.indexOf('.'), starting_string.length);
remaining_string = starting_string.substring(0,starting_string.indexOf('.'));
} else {
remaining_string = starting_string;
}
//if string is already 3 characters or less, do nothing
if (remaining_string.length > 3) {
//separate last 3 characters of string from rest of string
var final_three = remaining_string.substring(remaining_string.length - 3, remaining_string.length);
remaining_string = remaining_string.substring(0, remaining_string.length - 3);
//if not first group of 3, add new group before old group with comma, else set to new group
ending_string = (typeof(ending_string) == 'undefined') ? final_three + ((typeof(decimal_substring) == 'undefined') ? '' : decimal_substring) : final_three + ',' + ending_string;
//call function again if more than 3 digits remaining to process, else add to end string
if (remaining_string.length > 3) {
ending_string = FormatMoneyAmount(remaining_string, ending_string);
} else {
ending_string = remaining_string + ',' + ending_string;
}
} else {
ending_string = (typeof(ending_string) == 'undefined') ? remaining_string : remaining_string + ',' + ending_string + ((typeof(decimal_substring) == 'undefined') ? '' : decimal_substring);
}
}
return ending_string;
}
The first thing to do is check the format of the string, since you will have two code paths depending on the result:
if (typeof num = "string" && num.slice(0,1) == "(" && num.slice(-1) == ")") {
// String is in the format (x), so we just need to return that number
return num.slice(1,-1) + " units left";
}
The next part is to check if the number is less than 1, indicating that it is cents and not whole dollars. If it is less than 1, multiplying it by 100 will give you the number of cents you're after:
if (+num < 1)
// 0.0580 * 100 = 5.8
return (num * 100) + " cents";
else
return +num + "$";

How to use Javascript math on a version number

I use jQuery to get the browser version like this:
var x = $.browser.version;
I get a string like this: 1.9.1.1
Now, I want to do an evaluation so if x is >= 1.9.1 then do some stuff. Unfortunately, with multiple decimal points, I cannot do a parseFloat() because it converts 1.9.1.1 to simply 1.9, and the if evaluation would match a 1.9.0 version (which I do not want).
Has someone figured out a way to accomplish turning a version number (with multiple decimals) into something that can be used as a number for evaluation (or some other way to accomplish what I am trying to do here)?
Thanks -
You could do something with string.split and then do a digit by digit comparison
// arr[0] = 1
// arr[1] = 9
// arr[2] = 1
// arr[3] = 1
var arr = ($.browser.version).split('.');
The following is taken from this post
This is a function that will parse your version string and give you back a JSON object
function parseVersionString (str) {
if (typeof(str) != 'string') { return false; }
var x = str.split('.');
// parse from string or default to 0 if can't parse
var maj = parseInt(x[0]) || 0;
var min = parseInt(x[1]) || 0;
var bld = parseInt(x[2]) || 0;
var rev = parseInt(x[3]) || 0;
return {
major: maj,
minor: min,
build: bld,
revision: rev
}
}
Then you could use the following syntax
var version = parseVersionString($.browser.version);
// version.major == 1
// version.minor == 9
// version.build == 1
// version.revision == 1
Here's another version of versionCmp():
function versionCmp(v1, v2) {
v1 = String(v1).split('.');
v2 = String(v2).split('.');
var diff = 0;
while((v1.length || v2.length) && !diff)
diff = (+v1.shift() || 0) - (+v2.shift() || 0);
return (diff > 0) - (diff < 0);
}
Another possibility would be to assign a numeric value to each version number:
function valueOfVersion(ver) {
ver = String(ver).split('.');
var value = 0;
for(var i = ver.length; i--;)
value += ver[i] / Math.pow(2, i * 8) || 0;
return value;
}
This only works if each digit is less than 256 (because of the hard-coded divisor) and has a limited precision (ie the version strings can't get arbitrarily long).
You need to treat each portion of the string as a seperate integer, so split and iterate, and cmp:
// perform cmp(a, b)
// -1 = a is smaller
// 0 = equal
// 1 = a is bigger
function versionCmp(a, b) {
a = a.split(".");
b = b.split(".");
for(var i=0; i < a.length; i++) {
av = parseInt(a[i]);
bv = parseInt(b[i]);
if (av < bv) {
return -1;
} else if (av > bv) {
return 1;
}
}
return 0;
}
console.log(versionCmp("1.1.2.3", "1.2.1.0")); // should be -1
console.log(versionCmp("1.19.0.1", "1.2.0.4")); // should be 1
console.log(versionCmp("1.2.3.4", "1.2.3.4")); // should be 0
You could remove all dots and then parse it as an integer.
Take note tho, this solution doesn't work in the long term.

Categories