Capitalize only the first letter after colon with regex and JavaScript?


To capitalize only the first letter, use the concept of regular expression along with toUpperCase(). Since the toUpperCase() capitalize the entire string, we need to use Regex to only capitalize the first letter after colon.

Let’s say the following is our string −

var objectValues='fullName: john Smith';

Here’s the complete code to capitalize only the first letter after colon −

Example

var objectValues='fullName: john Smith';
function capitalizeFirstAfterTheColon(value){
   return value.replace(/([:\?]\s+)(.)/g, function(data) {
      return data.toUpperCase();
   });
}
console.log(capitalizeFirstAfterTheColon(objectValues));

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo85.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo85.js
fullName: John Smith

Updated on: 07-Sep-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements