Joel Peralta
Joel Peralta

Reputation: 19

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

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

Upvotes: -3

Views: 2303

Answers (4)

Ahmäd LP SN
Ahmäd LP SN

Reputation: 51

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)

Upvotes: 0

Sebastian Simon
Sebastian Simon

Reputation: 19485

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”.

Upvotes: 1

Yosvel Quintero
Yosvel Quintero

Reputation: 19070

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)

Upvotes: 0

xdhmoore
xdhmoore

Reputation: 9886

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);

Upvotes: 0

Related Questions