简体   繁体   中英

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

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.

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)

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM