How to replace numbers with letters with regular expressions in JavaScript?

2.1k Views Asked by At

I have a string of digits and letters like this:

let cad = "123941A120"

I need to convert that with these substitutions: A = 10, B = 11, C = 12, …, Z = 35. For example, the string above would result in the following, with A replaced by 10: 12394110120.

Another example:

Input:  158A52C3
Output: 1581052123
4

There are 4 best solutions below

0
xdhmoore On BEST ANSWER

This will do it without having to map all the letter codes, with the assumption that adjacent letters have adjacent codes...

result = "158A52c3".replaceAll(/[A-Z]/ig, (c) => {
    offset = 10;
    return c.toUpperCase().charCodeAt(0) - "A".charCodeAt(0) + offset;
})
    
console.log(result);

0
Yosvel Quintero On

You can do:

const arr = [
  { A: 10 },
  { B: 11 },
  { C: 12 },
  // ...
]

const input = '158A52C3'
const output = arr.reduce((a, c) => {
  const [[k, v]] = Object.entries(c)
  return a.replace(new RegExp(k, 'g'), v)
}, input)

console.log(output)

0
Ahmäd LP SN On

You can do the following:

const letters = {
'A':10,
'B':11,
'C':12
}
let cad = '123941A120'
for(let L in letters){
cad = can.replace(L,letters[L])
}
console.log(cad)
0
Sebastian Simon On

What you’re trying to do is to convert each digit to base 10. As each digit is from the range 0, 1, …, 8, 9, A, B, …, Y, Z, you’re dealing with a base-36 string. Therefore, parseInt can be used:

const convertBase36DigitsToBase10 = (input) => Array.from(input, (digit) => {
    const convertedDigit = parseInt(digit, 36);
    
    return (isNaN(convertedDigit)
      ? digit
      : String(convertedDigit));
  }).join("");

console.log(convertBase36DigitsToBase10("158A52C3")); // "1581052123"
console.log(convertBase36DigitsToBase10("Hello, world!")); // "1714212124, 3224272113!"


If you really want to stick to regex, the answer by xdhmoore is a good starting point, although there’s no need for “regex dogmatism”.