应该是写正则表达式,但是我实在写不出来
'A2B3'.replace(/(([a-zA-Z]+)(\d+))/g, (match, content, char, repeat) => String(char).repeat(repeat))
function repeat(string) {
let result = "";
let count = 0;
let letter = "";
let repeatString = "";
let numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
while (count < string.length) {
if (!numbers.includes(string[count])) {
if (repeatString !== "") {
result += letter.repeat(repeatString);
repeatString = "";
letter = string[count];
} else {
letter += string[count];
if (count === string.length - 1) {
result += letter;
}
}
} else {
repeatString += string[count];
if (count === string.length - 1) {
result += letter.repeat(repeatString);
}
}
count++;
}
return result;
}
可以尝试下根据 12345789 对字符串截取
拿到数字前的字母和数字
组合成一个类似这样的数组
[
{ label: 'A', num: 2 },
{ label: 'B', num: 3 }
]
然后根据num和label组成新的字符串
"A2B3".match(/[a-zA-Z]+\d+/g).map(_text=>_text.match(/[a-zA-Z]+/)[0].repeat(_text.match(/\d+/)[0])).join("")
进行了简单测试,有错误别说太狠
拿走不谢
var str = 'a2b3c12d123'
console.log(getMyString(str))
function getMyString(str) {
var re = /[a-zA-Z](\d+)/g
var list = str.match(re)
var objList = list.map(item => {
var 字母 = item.match(/[a-zA-Z]/)[0]
var 数字 = item.match(/\d+/g)
数字 = parseInt(数字)
return {
字母,
数字
}
})
var result = objList.map(obj => {
return obj.字母.repeat(obj.数字)
}).join('')
return result
}
8 回答4.6k 阅读✓ 已解决
6 回答3.3k 阅读✓ 已解决
5 回答2.8k 阅读✓ 已解决
5 回答6.3k 阅读✓ 已解决
4 回答2.2k 阅读✓ 已解决
4 回答2.8k 阅读✓ 已解决
3 回答2.4k 阅读✓ 已解决