Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to capitalize first and last letter of each word not working

Tags:

javascript

I created a function that given any string will return the string with the first and last letter of each word capitalized. So far it works in some words, not on others, can someone help me figure out why?

function Capitalize(str) {
  var spl = str.split(" "); 
  var words = [];
  for (let i = 0; i < spl.length; i++) {
    //For every word
    for (let j = 0; j < spl[i].length; j++) {
      //For every letter in each word
      var word = spl[i];
      var size = spl[i].length;
      var firstLetterCapital = word.replace(word[0], word[0].toUpperCase()); //Creates new array
      var LastLetterCapital = firstLetterCapital.replace(
        word[size - 1],
        word[size - 1].toUpperCase()
      );
    }
    words.push(LastLetterCapital);
  }
  console.log(words.join(" "));
}

Capitalize("hello there");

It works when I type : Capitalize("my name is john smith"), but not with Capitalize("hello there")

I know it's a complete mess and probably a very bad way to do it, but I started programming a month ago so give me a break :)

like image 585
Viny Ziks Avatar asked Dec 29 '19 21:12

Viny Ziks


3 Answers

@symlink has already explained why it is "HellO ThEre" instead of "Hello TherE". He also has given a solution to explicitly target first and last character of the string. I have accomplished not much different than already posted by members, except for .. "may be" a little more explanation.

You can break the entire problem in these four steps.

  1. Get all the words into an array.
  2. Create a function, that takes each word and targets first and last character, changes it and returns the changed word.
  3. Apply a mapping step using the function created above (in step 2) to the entire array of words (obtained in step 1).
  4. Join the transformed array, obtained in step 3, using a blank space as a separator.

I have written two functions that accomplish this task. I am sorry for long name of functions. It helps me keep track of things in a complex program (especially when I am in a hurry!).

Step 2 function

function Capitalize_FirstAndLast_One_Word(word){
// Split the string in array for easy access/manipulation by indexing
    Split_String = word.split("")
// Target the first word
    Split_String[0] = Split_String[0].toUpperCase();
// Target the last word
    Split_String[Split_String.length - 1] = Split_String[Split_String.length - 1].toUpperCase();
// Join the array into a single word
    Joined_Back = Split_String.join("")
    return Joined_Back;
}

Step 1, 3 and 4 function

function Capitalize_Entire_String(str){
 Regular_Exp = new RegExp(/\w+/g);  

//Below is step 1
 MatchedArray = str.match(Regular_Exp);

//Below is step 3
 ConvertedArray = MatchedArray.map(Capitalize_FirstAndLast_One_Word);

// Below is step 4
 ReturnedString = ConvertedArray.join(" ");
 console.log(ReturnedString);
 return ReturnedString;
}

Now you have everything. You can use the function like below.

Capitalize_Entire_String("hello there");
Capitalize_Entire_String("hello there this is a test");

Hope this helps. I am sorry if this turned out to be a redundant answer for you.

like image 113
Amit Avatar answered Oct 16 '22 03:10

Amit


Reason your code don't work is the use of replace(). replace() will always replace the first character found.

There is absolutely no reason to run a nested loop. You can achieve this using a single loop.

function cap(str){
  let spl = str.split(' ');
  for(let i = 0; i < spl.length; i++){
    let temp = spl[i];
    temp = temp[0].toUpperCase() + temp.slice(1)
    temp = temp.slice(0,-1) + temp[temp.length - 1].toUpperCase();
    spl[i] = temp;
  }
  return spl.join(' ');
}

console.log(cap("a quick brown fox"))

An easier way is to use map() and template strings.

const cap = str => str
                     .split(' ')
                     .map(x => (
                         x.length === 1 ? 
                             x.toUpperCase() : 
                            `${x[0].toUpperCase()}${x.slice(1,-1)}${x[x.length -1].toUpperCase()}`)
                     )  
                     .join(' ')

console.log(cap("a quick brown fox"))
like image 37
Maheer Ali Avatar answered Oct 16 '22 03:10

Maheer Ali


To simplify the function, you could split the string into an array, map each word to the desired format, and join it together into a string again.

function Capitalize(str){
	return str.split(" ").map((word) => word.charAt(0).toUpperCase() + 
		(word.length > 2 ? word.substring(1, word.length - 1) : "") + 
		(word.length > 1 ? word.charAt(word.length - 1).toUpperCase() : "")).join(" ");
}

console.log(Capitalize("i want to capitalize first and last letters"));
like image 37
Aaron Plocharczyk Avatar answered Oct 16 '22 02:10

Aaron Plocharczyk