js实现
// 字符串下划线转驼峰
const formatToHump = (value) => {
return value.replace(/\_(\w)/g, (_, letter) => letter.toUpperCase())
}
// 字符串驼峰转下划线
const formatToLine = (value) => {
return value.replace(/([A-Z])/g, '_$1').toLowerCase()
}
Java实现
private static final char UNDERLINE='_';
/**
* 下划线 转 驼峰
* @param param
* @return
*/
public static String underlineToCamel(String param){
if (param==null||"".equals(param.trim())){
return "";
}
int len=param.length();
StringBuilder sb=new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c = Character.toLowerCase(param.charAt(i));
if (c == UNDERLINE){
if (++i<len){
sb.append(Character.toUpperCase(param.charAt(i)));
}
}else{
sb.append(c);
}
}
return sb.toString();
}
/**
* 驼峰命名转为下划线命名
* @param para
* @return
*/
public static String HumpToUnderline(String para){
StringBuilder sb=new StringBuilder(para);
int temp=0;//定位
if (!para.contains("_")) {
for(int i=0;i<para.length();i++){
if(Character.isUpperCase(para.charAt(i))){
sb.insert(i+temp, "_");
temp+=1;
}
}
}
return sb.toString().toUpperCase();
}