简体   繁体   English

JavaScript中的正则表达式如何用字母替换数字?

[英]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 .我需要用这些替换来转换它:A = 10, B = 11, C = 12, ..., Z = 35。例如,上面的字符串将导致以下结果,将A替换为1012394110120

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.您要做的是将每个数字转换为以 10 为基数。由于每个数字都来自 0、1、...、8、9、A、B、...、Y、Z 范围,因此您正在处理一个基数-36 字符串。 Therefore, parseInt can be used:因此,可以使用parseInt

 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.如果您真的想坚持使用正则表达式, xdhmoore 的答案是一个很好的起点。

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...这样做无需 map 所有字母代码,假设相邻字母具有相邻代码......

 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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