I need to convert Excel-like cell ranges into a numeric format in JavaScript. The format I am aiming for is [rowStart, columnStart, rowEnd, columnEnd]
.
For example, a cell range like "A1:B3" should be converted to "1:1:3:2", and a range like "AA1:AAV5" should become "1:27:5:724".
I am struggling to come up with a way to convert the column letters to numbers, especially when the column range exceeds ‘Z’ and starts from ‘AA’, ‘AB’, and so on.
Here is what I have tried so far:
function parseCellRange(cellRange) {
// Split the range into start and end
let [startCell, endCell] = cellRange.split(':');
// Split startCell and endCell into row and column
let startColum = startCell.match(/[a-zA-Z]+/g);
let startRow = startCell.match(/(d+)/)[1];
let endColumn = endCell.match(/[a-zA-Z]+/g);
let endRow = endCell.match(/(d+)/)[1];
// Convert column letters to numbers
// This is where I am stuck
// Generate new cell range format
let newCellRange = [rowStart, columnStart, rowEnd, columnEnd]
return(newCellRange)
}
// Tests
parseCellRange("A1:B3"); // Should return [1, 1, 3, 2]
parseCellRange("AA1:AAV5"); // Should return [1, 27, 5, 724]
3
Answers
You could a function to convert a series of letters to a number (see also here) and use one regex-replace operation to make the final conversion:
This returns the text version as you described at the top of your question. If you want arrays, like specified in your code comments, then use this version of
parseCellRange
:You can consider the column name as a 26-based number and then you want to convert it to a decimal number:
For example AAV, the equation is:
Here is a working solution:
I build this class that works with any letters array.