anyway around using trim() function without changing majority of the code?
function titleCase(str) {
let str1 = '';
str = str.toLowerCase();
let arr = str.split(' ');
for (let i = 0; i < arr.length; i++) {
str1 += arr[i].replace(/^\S/, (x) => x.toUpperCase()) + ' ';
}
return str1.trim();
}
console.log(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT"));
you have a line in your for loop (in the original code) that does the replacing and then it concats a ’ ’ to the string (so the ’ ’ is added each time right?)
Just put the + ’ ’ part as a separate step (inside the for loop) and make it happen for every i except the last one.
function titleCaseWord(word) {
return word.replace(/^\S/, x => x.toUpperCase());
// Or this:
// return word[0].toUpperCase() + word.slice(1);
}
So
function titleCase(str) {
const words = str.split(' ');
const titlecasedWords = [];
// Any loop would do:
for (const word of words) {
let w = titleCaseWord(word);
titlecasedWords.push(w);
}
return titlecasedWords.join(' ');
}
Same as
function titleCase(str) {
return str.split(' ').map(titleCaseWord).join(' ');
}
function titleCase(str) {
str1 = ‘’;
str = str.toLowerCase();
let arr = str.split(’ ');
for (let i = 0; i < arr.length-1; i++) {
arr[i].replace(/^\S/, (x) => x.toUpperCase());
}
str1 = arr.join(" ");
return str1;
}
console.log(titleCase(“HERE IS MY HANDLE HERE IS MY SPOUT”));
hmmm doesnt work… either it doesnt capitalize or doesnt save it… what im failing to understand is how i can write the same code for every value of i except the last value i.e. i == arr.length-1
edit: would this do the trick…
function titleCase(str) {
str1 = ‘’;
str = str.toLowerCase();
let arr = str.split(’ ');
for (let i = 0; i < arr.length; i++) {
if (i < arr.length - 1) {
str1 += arr[i].replace(/^\S/, (x) => x.toUpperCase()) + ’ ';
} else {
str1 += arr[i].replace(/^\S/, (x) => x.toUpperCase());
}
}
return str1;
}
console.log(titleCase(“HERE IS MY HANDLE HERE IS MY SPOUT”));
// Basic Algorithm Scripting: Title Case a Sentence
function titleCase(str) {
// Regular expression matches first char of all words in the string
// with any non-whitespace character that is the beginning of the string
// OR has a space in front of it
let regex = new RegExp(/(^|\s)\S/, "gi");
// First convert all chars to lower case, then apply upper case to all regex matches
str = str.toLowerCase().replace(regex, (x) => x.toUpperCase());
return str;
}
console.log(titleCase("sHoRt AnD sToUt"));