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

write a python program to capitalize first and last letters of each word of a given string
python capitalize first letter of words in string
c program to capitalize first letter of every word in a string
capitalize first and last letter of each word in a line in java
c++ program to capitalize first letter of every word in a string
pandas capitalize first letter of each word
java program to capitalize first and last letter of each word in a line
python program to read a file and capitalize the first letter of every word in the file

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 :)

@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.

Python: Capitalize first and last letters of each word of a given string , Python Exercises, Practice and Solution: Write a Python program to capitalize first and last letters of each word of a given string. 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 o

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"))

Capitalize the first and last character of each word in a string , Capitalize the first and last character of each word in a string. 09-04- Approach. Create a character array of the String; Run a loop from the first letter to the last letter. Driver code. int main() function FirstAndLast( $str ). In this tutorial, we will learn how to capitalize the first letter of each word in a string. The user will enter the string. Our program will save it in a variable. Then using .title() method, we will convert the first letter of each word to capital and save the string in a different variable. Finally, the program will print out the result.

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"));

Program to convert first character uppercase in a sentence , Last Updated: 24-04-2020 To capitalize each word, call the toLowerCase() method to put the string in lowercase format. is not space then call the toUpperCase() method to put the first letter of word in uppercase We can easily work upon ascii_array and convert the starting lowercase characters of� string_name.capitalize() string_name: It is the name of string of whose first character we want to capitalize. Parameter: The capitalize() function does not takes any parameter. Return value: The capitalize() function returns a string with the first character in capital. Below is the python program to illustrate capitalize() function:

Congrats on starting out programming...

You can use this to achieve what you want to do

function capitalizeFirstAndLastLetters (str) {
    const words = str.split(" "); // Split the string into words
    const modified = [];

    for (const word of words) {
        if (word.length <= 2) {
            modified.push(word.toUpperCase()); // If the word less than 3 characters, the whole word is capitalized
            continue;
        }

        var firstCapital = word[0].toUpperCase(); // word[0] gets the first index of the string (I.e. the first letter of the word)
        var lastCapital = word.slice(-1).toUpperCase(); // The slice function slices a portion of the word. slice(-1) gets the last letter
        var middlePart = word.slice(1, -1); // slice(1, -1) means start slicing from the second index (I.e. 1) and ignore the last index

        modified.push(firstCapital + middlePart + lastCapital);
    }

    return modified.join(" "); // Join each element in the modified array with a space to get the final string with each words first and last letters capitalized
}

capitalizeFirstAndLastLetters("hello there I am a boy"); // "HellO TherE I AM A BoY"

How to Change Case in Excel: Capitalize First Letter (or ALL), There is also a function that capitalizes the first letter of proper names and places. No problem, you can still follow the exact same steps. It could also be multiple words such as first and last names, cities and states,� You will see that the first letter of each word in cells have been capitalized. Capitalize the First Letter of Each Word with VBA Code You can also use an Excel VBA macro to achieve the result of capitalizing the first letter of each word in cells.

This expression:

var LastLetterCapital = firstLetterCapital.replace(
    word[size - 1],
    word[size - 1].toUpperCase()
  );

Is replacing the first occurrence of the character "e" in "There" with an uppercase "E".

Explanation

The replace() function first translates the first param: word[size - 1] to the literal character "e", then replaces the first occurrence of that character with the uppercase "E", resulting in the string "ThEre".

Solution

Use a regular expression as your first parameter instead, to ensure that the last character is targeted, regardless of whether or not that same character shows up anywhere else in the word:

  var LastLetterCapital = firstLetterCapital.replace(/.$/, word[size - 1].toUpperCase());

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

Capitalize("hello there");

Function to capitalize first letter in each word in string but forces all , Function to capitalize first letter in each word in string but forces all other letters to be lowercase. Follow. 364 views (last 30 days) the string is set to lowercase and then the first letters of each word are indexed but I am not sure exactly how:. Capitalize the first letter only or the first letter of each word in text string cells With the help of Kutools for Excel’ s Change Case utility, you can quickly change the text strings to upper case, lower case, proper case, sentence case and so on.

Python Lower and Upper: Capitalize String, Python program that uses upper, lower value = "Tree" # Uppercase the string. x This method affects only the first letter in a string. If the first character is not a letter, nothing happens. Warning: Title will capitalize words that are not supposed to be capitalized, like "of" This reduces work but may introduce complexity. Function to capitalize first letter in each word Learn more about matlab, function, uppercase, live script 362 views (last 30 days) Olivia on 23 Nov 2013. Vote

How to Capitalize the First Letter of Each Word in Microsoft Word , Pullman holds a Master of Arts degree in Writing from Rowan University. Related. How to Conduct Employee Focus Groups � How to Alphabetize Last Names in�

Change text capitalisation in Pages on Mac, You can also quickly make selected text all uppercase or lowercase or format text as a title, with the first letter of each word capitalised. Capitalise sentences�

Comments
  • Can you show your function?
  • var LastLetterCapital = firstLetterCapital.replace( word[size - 1], word[size - 1].toUpperCase() ); makes no sense, what happens if the letter is somewhere else in the word?
  • @epascarello Where else would the last letter in the word be? Caesar cipher, by George!
  • What is the use of the j loop to iterate over characters when you need to work only on words?
  • Ask yourself why you have an inner loop. You never actually use j.
  • Thanks for the help !!
  • This capitalizes the first and last letter of the entire string, not each word, though.
  • This works but I think as he said he is new to programming (1 month ago) you might need to explain this a bit more for him to understand what is going on here as he probably doesn't know what this does
  • True, added some explanation.
  • Yeah, indeed I had absolutely no idea what you had done there :), thanks for the reply and help
  • I didn't know if I was supposed to start with lowercase or uppercase letter, just used the one that looked better :) Thanks!
  • One may argue that the function Capitalize is the only exception to the above rule ;-)