Skip to content

Instantly share code, notes, and snippets.

@MorenoMdz
Last active April 29, 2018 17:21
Show Gist options
  • Save MorenoMdz/0fa75468982750488df27e4acbc79fc6 to your computer and use it in GitHub Desktop.
Save MorenoMdz/0fa75468982750488df27e4acbc79fc6 to your computer and use it in GitHub Desktop.
/**
* Capitalize the first letter of each word
* 1) Create an array of words separating by spaces " " with split
* 2) At each word get the element 0 and capitalize it in a loop
* 3) Concatenate the words back into a string
*/
function LetterCapitalize(str) {
var words = str.split(" ");
// for each index, at the index of words do grab the substring from 0 to 1 (first letter)
// and uppercase it, the concatenate the rest (from 1 to end with .substring(1)).
for (var i = 0; i < words.length; i++) {
words[i] = words[i].substring(0, 1).toUpperCase() + words[i].substring(1);
}
return words.join(" ");
}
/* Using Regex*/
function LetterCapitalize2(str) {
// our regex [a-z] matches every alphabetic character in the string
// but the \b before it specifies a word boundary, in other words, nothing can
// come before those letters therefore selecting every word in the string
return str.replace(/\b[a-z]/gi, function(char) {
return char.toUpperCase();
});
}
LetterCapitalize("hello world from coderbyte");
/* Using MAP and Regex*/
function LetterCapitalize(str) {
return str
.split(/s+/)
.map(function(word) {
return word[0].toUpperCase() + word.slice(1);
})
.join(" ");
}
/* Using the string array index */
function LetterCapitalize3(str) {
var words = str.split(/ /);
str = "";
for (var i = 0; i < words.length; i++) {
// at the current index of words array and first letter ([0]) uppercase it
// then concat with the rest
var word = words[i][0].toUpperCase() + words[i].substring(1);
if (str != "") str += " ";
str += word;
}
// code goes here
return str;
}
/* Concat */
function LetterCapitalize4(str) {
// break the string at every space
return (
str
.split(" ")
// at each mapped item uppercase the first letter
.map(item =>
item[0]
.toUpperCase()
// concat it slicing from the second letter foward ((1) and re join with ' ' space
.concat(item.slice(1))
)
.join(" ")
);
}
/* Another one */
function LetterCapitalize(str) {
let words = str.split(" ");
for (let i = 0; i < words.length; i++) {
words[i] =
words[i].substring(0, 1).toUpperCase() +
// pass the length of the word (at index) as the end mark for substring, from 1 to end
words[i].substring(1, words[i].length); // not sure if passing the second param is needed
}
str = words.join(" ");
return str;
}
/* Another regex */
function LetterCapitalize(str) {
return str.replace(/\b(\w)/g, function(match) {return match.toUpperCase()});
}
LetterCapitalize(readline());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment