Skip to content

Instantly share code, notes, and snippets.

@JeffJacobson
Last active August 26, 2023 10:42
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save JeffJacobson/3841577 to your computer and use it in GitHub Desktop.
Save JeffJacobson/3841577 to your computer and use it in GitHub Desktop.
Splits camelCase or PascalCase words into individual words.
/**
* Splits a Pascal-Case word into individual words separated by spaces.
* @param {Object} word
* @returns {String}
*/
function splitPascalCase(word) {
var wordRe = /($[a-z])|[A-Z][^A-Z]+/g;
return word.match(wordRe).join(" ");
}
/**
* Splits a camelCase or PascalCase word into individual words separated by spaces.
* @param {Object} word
* @returns {String}
*/
function splitCamelCase(word) {
var output, i, l, capRe = /[A-Z]/;
if (typeof(word) !== "string") {
throw new Error("The \"word\" parameter must be a string.");
}
output = [];
for (i = 0, l = word.length; i < l; i += 1) {
if (i === 0) {
output.push(word[i].toUpperCase());
}
else {
if (i > 0 && capRe.test(word[i])) {
output.push(" ");
}
output.push(word[i]);
}
}
return output.join("");
}
/** Splits a camel-case or Pascal-case variable name into individual words.
* @param {string} s
* @returns {string[]}
*/
function splitWords(s) {
var re, match, output = [];
// re = /[A-Z]?[a-z]+/g
re = /([A-Za-z]?)([a-z]+)/g;
/*
matches example: "oneTwoThree"
["one", "o", "ne"]
["Two", "T", "wo"]
["Three", "T", "hree"]
*/
match = re.exec(s);
while (match) {
// output.push(match.join(""));
output.push([match[1].toUpperCase(), match[2]].join(""));
match = re.exec(s);
}
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment