let str2 = "personFirstName"
function parseStrToHungarian(str){
let newStr=""
for(var i=0;i<str.length;i++){
if(/^[A-Z]$/.test(str[i])){
newStr = newStr+"_"+str[i].toLowerCase()
}else{
newStr = newStr+str[i]
}
}
return newStr
}
console.log(parseStrToHungarian(str2))
上面这段代码和匈牙利命名法转驼峰命名差不多,有兴趣的可以去看一下。
function cameTostr(str){
//使用replace方法 将匹配到的大写转换成字符串
return str.replace(/[A-Z]/g,s=>s.toLocaleLowerCase())
}
这个也是用了replace替换。代码量相对较少。😀