javascriptregexbase36

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

Solution

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