Skip to content

Instantly share code, notes, and snippets.

@danielmcq
Last active January 22, 2018 20:40
Show Gist options
  • Select an option

  • Save danielmcq/2392d019a6223f329712324811a643ad to your computer and use it in GitHub Desktop.

Select an option

Save danielmcq/2392d019a6223f329712324811a643ad to your computer and use it in GitHub Desktop.
Increment Excel column letters
// Only supports positive numbers for now
function column (letters, numberOfColumnsAway=0) {
let newColumnLetters = letters.trim().toUpperCase()
for (let i = 0; i < Math.abs(numberOfColumnsAway); i++) {
newColumnLetters = incrementColumnLetters(newColumnLetters)
}
return newColumnLetters
}
function incrementColumnLetters (letters) {
const INPUT_ERROR_MSG = 'Input is not a string of letters.'
if (!letters) throw new TypeError(INPUT_ERROR_MSG)
const startLetter = 'A'
const endLetter = 'Z'
const endLetterCode = endLetter.charCodeAt()
const letterRangeRE = new RegExp(`[${startLetter}-${endLetter}]`,'g')
const lettersList = letters.trim().toUpperCase().match(letterRangeRE)
if (!Array.isArray(lettersList)) throw new TypeError(INPUT_ERROR_MSG)
let i,c,letter
const incrementedLettersList = []
for (i=lettersList.length-1,c=1; i>=0||c>0; i--) {
if (lettersList[i]) letter = lettersList[i]
else letter = startLetter, c--
if (c>0) {
letter = String.fromCharCode(letter.charCodeAt() + c--)
if (letter.charCodeAt() > endLetterCode) letter = startLetter, c++
}
incrementedLettersList.unshift(letter)
}
return incrementedLettersList.join('')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment