Search code examples
javascriptstring-comparisonalphanumeric

Javascript Alphanumeric String Comparison


I have a list of string 'X1','X2','X3','S1','S2','S3',etc. I want to do the following comparison

var string = INPUT STRING;
if( string > 'X10' ){
    DO THIS
}else{
    DO THAT
}

In this case, if the input string is 'X8' then my code is returning X8 IS GREATER than X10. If there a way I can truly get X10 > X8?


Solution

  • You can split it into alphabetical and numeric parts. Assuming the alphabetical part is only one character,

    var alpha = string.charAt(0);
    var num = string.substring(1) | 0; // | 0 to cast to integer
    
    if (alpha > 'X' && num > 10) {
        …