我最近遇到了这个问题,需要做同样的事情:
employeeID应呈现为Employee ID
我发现这个来自zellwk的转换案例库加上一点额外的 reduce 函数对我有用:
import { toTitle } from "./convert-case.js";
// NB. Assumes sequential single chars can be concatenated
// ex. N B A Finals => NBA Finals
const reducer = (total, currentValue, currentIndex, arr) => {
if (
currentValue.length === 1 &&
!(currentIndex > 0 && arr[currentIndex - 1].length > 1)
) {
return total + currentValue;
} else {
return total + " " + currentValue;
}
};
const concatSingleChars = (title) => {
const arrTitle = title.split(" ");
return arrTitle.reduce(reducer);
};
const convertCase = (str) => {
const s = toTitle(str);
return concatSingleChars(s);
};
const tests = [
"colName",
"This_Is_A_title",
"And_How_About_thisOne",
"MaryHadALittleLamb",
"employeeID",
"N B A Finals",
"N B A Finals in L A",
"I Love L A"
];
const titles = tests.map((test) => {
return convertCase(test);
});
console.log(titles);