Ahm23
Ahm23

Reputation: 366

Specify Range of Numbers Javascript in Conditional Statement

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.

Upvotes: 0

Views: 145

Answers (2)

Nikkorian
Nikkorian

Reputation: 790

@Ahm23, Try this:

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

Upvotes: 1

guest271314
guest271314

Reputation: 1

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

Upvotes: 0

Related Questions