Skip to content

Instantly share code, notes, and snippets.

@cuixiping
Created April 9, 2018 07:20
Show Gist options
  • Save cuixiping/4a9642ea92f8b28d06776046c34d740b to your computer and use it in GitHub Desktop.
Save cuixiping/4a9642ea92f8b28d06776046c34d740b to your computer and use it in GitHub Desktop.
Excel表风格的字母列名转换为序号数字 Convert excel column name to number in javascript
/**
* Excel表风格的字母列名转换为序号数字
* Excel spreadsheet style column names are like A,B,C...,AA,AB,AC,...etc
* Sometimes we need to convert the letters name to number 1,2,3...,27,28,29,...etc
* Author: https://github.com/cuixiping
**/
//solution 1: best performance and best compatibility
function lettersToNumber(letters){
var chrs = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ', mode = chrs.length - 1, number = 0;
for(var p = 0; p < letters.length; p++){
number = number * mode + chrs.indexOf(letters[p]);
}
return number;
}
//solution 2: short code (es6 arrow function)
function lettersToNumber(letters){
return letters.split('').reduce((r, a) => r * 26 + parseInt(a, 36) - 9, 0);
}
//test:
['A', 'Z', 'AA', 'AB', 'ZZ','BKTXHSOGHKKE'].map(lettersToNumber);
// [1, 26, 27, 28, 702, 9007199254740991]
lettersToNumber('AAA'); //703
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment