【发布时间】:2017-11-07 15:41:50
【问题描述】:
基本上我想这样做:
我得到一个字符串"myVariableName" 并将其转换为:["my", "variable", "name"]
我尝试使用正则表达式来执行此操作,但似乎在我的结尾数组中有很多未定义。在这种情况下,变量名的两种可能情况是驼峰式和大蛇式。
const matchVariableNames = /(\b[a-z]+)|([A-Z][a-z]+)|(\b[A-Z]+)|(_[A-Z]+)/g;
const variableName = 'myVariable';
let words = [];
let regexMatches;
while (regexMatches = matchVariableNames.exec(variableName)) {
regexMatches.forEach((match) => {
words.push(match);
});
};
输出:
["my", "my", undefined, undefined, undefined, "Variable", undefined, "Variable", undefined, undefined]
undefined
【问题讨论】:
-
"myVariableName".match(/((?:^|[A-Z])[a-z]+)/g)从技术上讲,一些非字母字符可以用作 var 名称,但这可能就足够了,具体取决于您的 var 命名约定 -
console.log( "myVariableName" .replace(/^[a-z]|[A-Z]/g, function(v, i) { return (i === 0 ? "":" ")+ v.toLowerCase(); }).split(" ") )
标签: javascript arrays regex