Using only the first letter of a contraction as uppercase

One of the challenges I'm facing right now is how to properly capitalize the first letter of each word in a string while keeping all other letters in lowercase. Although I've dedicated countless hours to working on this, my code appears to be about 95% complete.

The only issue that remains is that when it comes across contractions like "I'm", it capitalizes both parts as separate words ("I" and "M") rather than just the "I". I even added a console.log to check what's happening, and it confirms that both letters are being capitalized in the same step. How can I ensure that only the initial letter is transformed?

function titleCase(str) {

  str = str.toLowerCase(); //convert everything to lowercase
  str = str.split(" "); //split the string into an array

  for(i = 0; i < str.length; i++){
    var strItem = str[i]; //retrieve item from array
    strItem = strItem.replace(/\b./g, function(m){ return m.toUpperCase(); }); //capitalize the first letter
   //console.log(strItem);
   str[i] = strItem; //update item in the array
  }

  str = str.join(" "); //merge array elements back into a string
  return str;
}

titleCase("I'm a little tea pot");

I appreciate your assistance with this matter.

Answer №1

It appears that your issue stems from using a global match in the replacer expression.

Please remove the g.

function titleCase(str) {
  str = str.toLowerCase();               // Convert to lowercase
  str = str.split(/\s+/);                // Transform string into an array  
  for (var i = 0; i < str.length; i++) {
    var strItem = str[i];                // Grab item in array
    strItem = strItem.replace(/\b./,
        function(m) {
              return m.toUpperCase();    // Capitalize it
        }
    );                           
    str[i] = strItem;                    // Update array with modified item
  }
    
  return str.join(" ");                  // Join array elements back into a string
}

document.body.innerHTML = titleCase("I'm a little tea pot");

Simplified

You can define a capitalCase function and utilize it as the callback function for each word.

function titleCase(str) {
  return str.split(/\s+/).map(captitalCase).join(' ');
}

function captitalCase(str) {
  return str.charAt(0).toUpperCase() + str.substring(1).toLowerCase();
}

document.body.innerHTML = titleCase("I'm a little tea pot");

Preserve White-Space

If white-space preservation is desired, you can replace all non-white-space character sequences with their corresponding capitalCase equivalent.

function titleCase(str) {
  return str.replace(/(\S+)/g, function(m) {
    return captitalCase(m);
  });
}

function captitalCase(str) {
  return str.charAt(0).toUpperCase() + str.substring(1).toLowerCase();
}

document.body.innerHTML = titleCase("I'm   a   little  \n  tea   pot");
body {
  white-space: pre;
}

Answer №2

My recommendation is to utilize

<string>.charAt(<index>)
in order to obtain the first letter of a string, and also use
<string>.slice(<index>)
to extract a portion of a string.

Suggestion: Once you have each word, consider using charAt() to capitalize the first letter, followed by taking a slice of the remaining part of the string and converting it to lowercase.

UPDATE:

Answer:

function upperFirstLetterInWords(str) {

  var totalString = "";
  //Extract words from the given sentence - 
  //Use regex /\s+/g to handle multiple spaces within the sentence.
  var words = str.split(" "); 

  //Iterate through each word...
  //Using a for loop since we are dealing with an array,
  //which is more efficient than using a forEach loop or lambda.
  for(var i = 0; i < words.length; ++i) {
     //Implement desired changes here.javascript:;
     totalString += words[i].charAt(0).toUpperCase() +
         words[i].slice(1).toLowerCase()  +
         " ";
  }

  //Trim any trailing spaces.
  return totalString.trim();

}

console.log(upperFirstLetterInWords("I'm A LitTle TEa POt."));

Answer №3

Just for fun, I decided to challenge myself and find an alternative javascript solution that didn't involve using regex:

var selectedParagraph = document.getElementsByTagName('p')[1];

var textUC = [];

function convertToTitleCase(element) {
var textLC = element.innerHTML.toLowerCase().split(' ');
for (var i = 0; i < textLC.length; i++) {
textUC[i] = textLC[i].charAt(0).toUpperCase() + textLC[i].slice(1);}
element.innerHTML = textUC.join(' ');
}

window.onload = convertToTitleCase(selectedParagraph);
<p>I'm a little tea pot</p>
<p>I'm a little tea pot</p>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Meteor, app has been upgraded and now receiving error message 'TypeError: check is not defined'

I've been in the process of updating an old meteor project that was running on a version even older than 1.0.0. The issue cropped up at Meteor 1.4.2.3, but strangely another app is working smoothly on the same version. After making several adjustment ...

Dealing with a jQuery/JavaScript issue involving thumbnail images

I am facing an issue with smooth transitions between thumbnail images in HTML list tags. I have Jquery listeners set up for mouseenter and mouseleave events that update a parent image when a thumbnail is hovered over. The problem arises when scrolling fro ...

Update a separate React component in response to the interaction with a different React component

Currently, I am working with a react component named Interest Category that showcases an initial set of Interest categories. Another react component called CreateInterestCategoryDialog, which functions as a modal, is responsible for creating a new entity I ...

Choose a column in a table and organize it in ascending or descending order with the help

Does anyone know how to use JavaScript (without frameworks or plugins) to select and sort a specific column in a table? <table> <thead> <tr> <td>Col1</td> <td>Col2&l ...

Encountered an error while trying to click the cookie button using Selenium: "object[] does not have a size or

I've been struggling to interact with a button inside a pop-up using Selenium, but I keep encountering this error: object [HTMLDivElement] has no size and location I initially tried to simply click the button since it is visible on the page and I wai ...

What causes the index to display [object Object] rather than an integer in React?

It has been a long time since I last worked with React, and now I'm facing an issue. Whenever I use console.log to display the index within the map function, my console output looks like this: https://i.stack.imgur.com/VbGmE.png However, the result ...

Showing the `ViewBag` data within the `@Html.DropDownListFor` method enclosed

I'm currently working with a DropDownListFor that is set up like this: <div class="form-horizontal" id=CurrencyDataBlock> @Html.DropDownListFor(model => model.Code, ViewBag.Currency as SelectList, "--Select Currency--", n ...

uWebSockets supporting multiple concurrent user sessions

To keep things simple, let's assume that my server is running just one uWebSockets instance: struct UserData { uWS::WebSocket<true, uWS::SERVER> *ws; bool logged_in = false; ID user_id; }; uWS::SSLApp() .ws<UserData>( ...

The Best Way to Filter Mongo Documents Using Nested Objects

Is there a way to locate a room by its ID and confirm that it includes the current player? Within my mongodb database, I have a collection of rooms that contain players who are users. const RoomSchema = new Schema({ players: [{ type: Schema.Types.Objec ...

Utilizing the import feature for structuring the routes folder in Express with Node.js

Recently, I made the switch to using ECMAScript (ES6) for my NodeJS Rest API with Express, and I've encountered a few challenges when working with the new keyword import In the past, I would organize my routes folder like this: Let's imagine th ...

Providing Node-server with Vue.js Server Side Rendering

I've been attempting to deploy the Hackernews 2.0 demo on my Digital Ocean droplet but have hit a roadblock. npm run start starts the server on port :8080. npm run build is used for production builds. The specific build tasks can be found below: ...

Cross-Origin Resource Sharing using Express.js and Angular2

Currently, I am attempting to download a PLY file from my Express.js server to my Angular/Ionic application which is currently hosted on Amazon AWS. Here is the Typescript code snippet from my Ionic app: //this.currentPlyFile contains the entire URL docum ...

showing sections that collapse next to each other

I am currently designing a portfolio website using HTML, CSS, and vanilla JavaScript. I have implemented collapsing sections that expand when clicked on. However, the buttons for these sections are stacked vertically and I want to place them side by side. ...

Error: Module 'fs' does not export the function 'existsSync' as requested

When I simulate the behavior of the fs module jest.mock('fs', () => { return { default: { readFileSync: () => { return CONTENT_DATA; }, existsSync: () => {}, }, }; }); Then I attempt to dynamically ...

Error in HTML Sorting

I've been experimenting with some code from this fiddle: http://jsfiddle.net/kutyel/5wkvzbgt/ but when I copy it into Notepad++ and run it, it only displays: <html> Id: {{result.id}} Product: {{result.name}} Price: {{result.price | currency} ...

Trigger the click event on the ul element instead of the li element using jQuery

Is there a way to make the click event only affect ul tags and not all li elements using jQuery? <!-- HTML --> <ul class="wrap"> <li>test1</li> <li>test2</li> <li>test3</li> </ul> I attemp ...

Passport.js is throwing an error due to an unrecognized authentication

I need to implement two separate instances of Passport.js in my application - one for users and one for admins, both using JWT authentication. According to the official documentation, the way to differentiate between them is by giving them unique names. W ...

Discover a method to conceal an element within a <div> by monitoring mouseover events in a separate <div> container

<div id="one-id"> <div id="some">Information</div> <div id="control"> <div id="value-1"> <img id="image-one-id" /> <img id="image-two-id" /> ...

What is the best way to create a scrollable tbody in an HTML table using React?

In my current project, I am using React, Node, Express, and Postgres to fetch data from a database. The issue I'm facing involves creating a scrollable table within a div that spans the entire screen width. Initially, I had to apply display: block to ...

Tips for gently scrolling instead of quickly scrolling all at once

As a novice in HTML, I have a question about navigation to an ID targeted by an anchor tag. For example: When I execute this code, it quickly jumps to the specified ID but I would like to incorporate animations. Is there a way to achieve this? ...