1

For example , I would like to compare 0-91 and 0-93 , in the logic I'm using , 0-93 is bigger than the 0-91 because I'm only looking at the numbers after 0-, which are 91 and 93 . Basically I'm building a form where it checks for ranges of numbers but in the form , the numbers could be typed in for example as 91 and 93 , but they are usually typed in as 0-91 and 0-93 , how can I write the javascript logic so that the 0- is ignore while comparing the two numbers ?

Basically convert 0-91 and 0-93 into integers 91 and 93 , then compare them.

2
  • 1
    Are the numbers always going to be in the form 0-x? Commented Jan 31, 2013 at 19:30
  • "0-93".match(/0-(\d+)/)[1]? Commented Jan 31, 2013 at 19:33

2 Answers 2

1

One way to do it would be :

var a = '0-91',
    b = '0-93',
    max = Math.max(a.slice(2), b.slice(2)), // for example
    max2 = Math.max(a.substr(-2), b.substr(-2)); // will work if a = "91" and b = "93"

Hope this helps

Sign up to request clarification or add additional context in comments.

9 Comments

and that would produce 91 and 93 .. Would they be of integer type though or still string ?
a.slice(2) would still be a "string", but parseInt(a.slice(2), 10); would be a "number"
This solution will not work when the user inputs just 93. You could parse the string with regular expressions. Something like this: "0-91".match(/[-]?(\d*)$/).pop() will return "93".
Edited my answer, it works with substr(-2); But using a regex will work with more than 2 digits.
@SvenI see .. so I should just use .match(/[-]?(\d*)$/).pop() for either 93 or 0-93 ??
|
0

If you want support for:

  • Range or no range ("0-93" or "93")
  • More or less digits ("0-999" or "9")

This is one way to solve it:

function numberFromInput(value) {
  return Number(value.match(/[-]?(\d*)$/).pop());
}

Math.max(numberFromInput("91"), numberFromInput("0-93"));

3 Comments

Thanks much Sven , so wthat would control either 91 or 0-93 .. but they would still be strings ? to make them integers I would have to add the parseInt in the function parseInt(Number(value.match(/[-]?(\d*)$/).pop())); ?
There are no integers in JavaScript, just Numbers! You can test this with 1.0 === 1. parseInt will also return a Number (with everything after the coma tossed away).
parseInt(Number(...)) is redundant. Just use parseInt.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.