-3

I have two variables, both containing text and numbers and I'm getting the wrong result when comparing them:

var x = "test_8"
var y = "test_11"
if(x > y){
    alert(x+" is greater than "+y);
}
else{
    alert(y+" is greater than or equal to "+x);
}

I get the alert saying test_8 is greater than test_11 but I should be getting the other alert. I'm guessing I would have to extract the 8 and 11 out as numbers but I'm not sure how to do that.

NiallMitch14
  • 1,198
  • 1
  • 12
  • 28

1 Answers1

1

It need to be converted to number for exact comparison.

    function getNum(str) {
        // it removes all non numeric, but regex can be differ according the str data which uses.
        return Number(str.replace(/\D+/,""));
    }

    var x = "test_8";
    var y = "test_11";

    if(getNum(x) > getNum(y)){
        alert(x+" greater than "+y);
    }
    else{
        alert(y+" greater than "+x);
    }
Jae Sung Park
  • 900
  • 6
  • 9
  • thanks, this was the way I got it fixed. I check if the variable has a number in it and convert it to a number if it does – NiallMitch14 Dec 21 '15 at 13:05