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
andY8
? – 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
2 Answers
Reset to default 5You 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!