一、題目示例:
思路:
1、匹配屬性名字符串中的大寫字母和數字
2、通過匹配后的lastIndex屬性獲取匹配到的大寫字母和數字的位置
3、判斷大寫字母的位置是否為首位置以及lastIndex是否為0,為0則表示匹配結束
4、將存放位置的數組進行從小到大排序,排序后將屬性名按照字符串的slice方法切割並使用下划線重組
5、遍歷對象的屬性名並使用函數改變為新的命名,從新賦值到新的對象上(也可以使用改變對象的ES6新語法)
6、注意,每次在調用函數后,需要清空之前存放位置的數組

二、實現代碼
let obj = {Id1: 1, idName1: 2, idAgeName1: 3};
let arr = []
function strReplace(str) {
const UP_CASE_REG =/[A-Z]/g;
const NUMBER_REG=/[A-Za-z][\d]/g
let newstr = ""
getIndex(UP_CASE_REG, str)
getIndex(NUMBER_REG, str)
arr.sort((a,b)=> a-b )
for(let i = 0;i < arr.length; i ++) {
if(i === 0) {
newstr += str.slice(0,arr[i]) + "_"
}
else {
newstr += str.slice(arr[i-1],arr[i]) + "_"
}
}
newstr += str.slice(arr[arr.length-1])
return newstr.toLowerCase()
}
function getIndex(reg, str) {
do{
reg.test(str)
if(reg.lastIndex !== 0 && reg.lastIndex-1 !== 0){//reg.lastIndex-1 !== 0判斷首字母是否大寫
arr.push(reg.lastIndex-1)
}
}while(reg.lastIndex > 0)
}
function strAllReplace(obj) {
let newObj = {}
Object.entries(obj).forEach(([key, value]) =>
{
newObj[strReplace(key)] = value
arr = []
})
return newObj
}
console.log(strAllReplace(obj))//{id_1: 1, id_name_1: 2, id_age_name_1: 3}

