最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Alphanumeric String Comparison - Stack Overflow

programmeradmin2浏览0评论

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

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?

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

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?

Share asked Jul 22, 2014 at 18:22 CamelCaseCamelCase 2333 gold badges6 silver badges17 bronze badges 3
  • 1 What is your expected result for paring X10 and Y8? – elixenide Commented Jul 22, 2014 at 18:24
  • I am going to pare string starting with same alphabet. – CamelCase Commented Jul 22, 2014 at 18:33
  • In that case, you need to do something like what @minitech suggests. – elixenide Commented Jul 22, 2014 at 18:33
Add a ment  | 

2 Answers 2

Reset to default 5

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) {
    …

If you're looking out for a natural sorting or parison of alphanumeric strings, you can try using the localeCompare() method.

It outputs a -1, 0 or 1 for results which are less than, equal or greater than respectively. It has some interesting options to provide as well. For instance, to get a natural alphanumeric sort (x10 < x8), you may pass the numeric: true option. To also make the case insensitive while paring the string, you may also pass sensitivity: 'base' option. This would pare the two strings value and VALUE as equal, ignoring the casings.

An example using both the options is below:

leftString.localeCompare(rightString, undefined, { numeric: true, sensitivity: 'base'})
// With this you would get following results
// X8 < X10
// X8 === x8

Hope this is useful. Cheers!

发布评论

评论列表(0)

  1. 暂无评论