比较包含数字的文本

时间:2015-12-21 12:27:40

标签: javascript

我有两个变量,都包含文本和数字,比较时我得到错误的结果:

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);
}

我收到警告说test_8大于test_11但是我应该得到另一个警报。我猜我必须提取数字8和11,但我不知道该怎么做。

1 个答案:

答案 0 :(得分:1)

需要将其转换为数字以进行精确比较。

    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);
    }