How7oHow7o
  • Home
  • Tools
    • All Tools
    • Image Tools
    • Text & String Tools
    • Video Tools
    • Developer Tools
    • PDF Tools
    • Calculators & More
  • Prank Screens
  • Learn
  • Blog
  • Contact
Reading: Capitalize All Words in JavaScript (ucwords Equivalent) + First Letter Uppercase
Share
Notification Show More
Font ResizerAa
How7oHow7o
Font ResizerAa
  • Tools
  • Prank Screens
  • Learn
  • Blog
Search
  • Home
  • Tools
    • All Tools
    • Image Tools
    • Text & String Tools
    • Video Tools
    • Developer Tools
    • PDF Tools
    • Calculators & More
  • Prank Screens
  • Learn
  • Blog
  • Contact
Follow US
© 2024–2026 How7o. All rights reserved.
How7o > Free Laravel, PHP, WordPress & Server Tutorials > Web Development > Capitalize All Words in JavaScript (ucwords Equivalent) + First Letter Uppercase
Web Development

Capitalize All Words in JavaScript (ucwords Equivalent) + First Letter Uppercase

how7o
By how7o
Last updated: February 6, 2026
6 Min Read
Capitalize all words in JavaScript with a ucwords-style function
SHARE

I ran into a small but annoying problem while working on a UI: I needed to capitalize all words in JavaScript—the same way PHP’s ucwords() works. JavaScript has toUpperCase(), but that turns everything into uppercase, not “Title Case” where each word starts with a capital letter.

Contents
  • What “capitalize all words” really means
  • The simple solution (ucwords equivalent)
  • My preferred version: handles multiple spaces better
  • Capitalize only the first letter of the whole string
  • Make it callable like a method (String prototype)
  • Advanced option: preserve spacing and punctuation with regex
  • Step-by-step guide (quick checklist)
  • Troubleshooting
    • 1) “It breaks when there are multiple spaces”
    • 2) “It turns ACRONYMS or names weird”
    • 3) “My string has hyphens or apostrophes”
    • 4) “What about Unicode languages?”
  • Official references (good to bookmark)
  • Related guides

So I built my own tiny ucwords()-style helper. In this post, I’ll show you the clean approach, a couple of improved versions, and the common pitfalls you’ll want to avoid.

What “capitalize all words” really means

When people say “capitalize all words,” they usually mean:

  • Make the first character of each word uppercase
  • Keep the rest of the characters as-is (or optionally lowercase them)
  • Handle extra spaces and odd input without breaking

Example:

this is a simple string
// becomes:
This Is A Simple String

The simple solution (ucwords equivalent)

If your strings are simple and space-separated, this is the quickest solution:

function ucwords(str) {
  return str
    .split(' ')
    .map(word => word ? word[0].toUpperCase() + word.slice(1) : '')
    .join(' ');
}

const simpleString = "this is a simple string";
console.log(ucwords(simpleString));
// This Is A Simple String

This works well for basic inputs, and it reads almost like PHP’s ucwords().

My preferred version: handles multiple spaces better

The first approach splits only on a single space. That can behave oddly when users paste text with multiple spaces or tabs. A safer approach is splitting on whitespace using a regular expression, and then joining back with a single space:

function ucwordsClean(str) {
  return str
    .trim()
    .split(/\s+/)
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');
}

console.log(ucwordsClean("   this   is\t\ta   test   "));
// This Is A Test

If you want to preserve the original spacing exactly as typed, skip this version and use the “regex replace” approach later in this post.

Capitalize only the first letter of the whole string

Sometimes you don’t want Title Case—just a sentence that starts with a capital letter. Here’s a clean helper:

function capitalizeFirstLetter(str) {
  if (!str) return str;
  return str.charAt(0).toUpperCase() + str.slice(1);
}

console.log(capitalizeFirstLetter("hello world"));
// Hello world

Make it callable like a method (String prototype)

In my original forum answer, I made it callable directly on a string, like simpleString.ucwords(). You can do that by extending String.prototype.

Here’s a practical implementation that supports two modes:

  • Title Case: capitalize all words
  • Sentence case: capitalize only the first letter of the string
String.prototype.ucwords = function (allowAll = true) {
  if (!this) return this;

  if (allowAll) {
    return this
      .trim()
      .split(/\s+/)
      .map(word => word.ucwords(false))
      .join(' ');
  }

  return this.charAt(0).toUpperCase() + this.slice(1);
};

const simpleString = "this is a simple string";
console.log(simpleString.ucwords());
// This Is A Simple String

Note: Extending native prototypes can be controversial in larger projects or shared codebases because it can cause conflicts. For personal utilities or tightly controlled code, it can be perfectly fine. If you’re building a library, prefer standalone functions.

Advanced option: preserve spacing and punctuation with regex

If you want to preserve the original spacing (multiple spaces, new lines) and just capitalize the first letter after every “word boundary,” a regex replace works nicely:

function ucwordsPreserveFormat(str) {
  return str.replace(/\b([a-z])/g, match => match.toUpperCase());
}

console.log(ucwordsPreserveFormat("this   is a\nsimple\tstring"));
// This   Is A
// Simple	String

This focuses on ASCII letters a-z. If you need full Unicode title-casing (for international text), you’ll likely want a library or more advanced logic.

Step-by-step guide (quick checklist)

  • Decide your goal: Title Case (each word) or Sentence case (first character only).
  • Pick your method:
    • Use split() + map() for simple strings.
    • Use split(/\s+/) for messy user input.
    • Use regex replace if you must preserve formatting exactly.
  • Add edge-case guards: handle empty strings, extra spaces, and unexpected input.
  • Optional: add a String.prototype method only if your project style allows it.

Troubleshooting

1) “It breaks when there are multiple spaces”

Use whitespace splitting:

str.trim().split(/\s+/)

2) “It turns ACRONYMS or names weird”

Most ucwords helpers only uppercase the first letter and keep the rest untouched. If you convert the rest to lowercase, you might break iPhone, API, or McDonald. If you need special title-casing rules, you’ll need extra logic (or keep the rest of each word unchanged).

3) “My string has hyphens or apostrophes”

A basic split-by-space approach won’t handle cases like rock-n-roll or don’t the way you might expect. If this matters, the regex approach is often better, but it depends on your exact formatting requirements.

4) “What about Unicode languages?”

toUpperCase() works with Unicode, but word detection with regex can get tricky. If your app needs robust international title-casing, consider a well-maintained i18n library.

Official references (good to bookmark)

  • MDN: String.prototype.toUpperCase()
  • MDN: String.prototype.replace()

Related guides

  • How to trim whitespace in JavaScript
  • JavaScript string methods you actually use
  • Regex basics for web developers

If you want the closest “PHP ucwords()” experience, the split + map version is usually enough. If you care about messy user input or preserved formatting, pick one of the improved versions above and you’re set.

TAGGED:Beginner TipsES6JavaScriptString MethodsString PrototypeText FormattingtoUpperCaseucwordsWeb Development

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
[mc4wp_form]
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article CSS page break for printing shown in a print preview layout CSS Page Break for Printing: How to Split a Web Page Into Multiple Printed Pages
Next Article Dynamically set site title and tagline in WordPress by country How to Dynamically Set Site Title and Tagline in WordPress (By Country)
Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

You Might Also Like

Laravel DataTables custom column search — filterColumn callback handles the search SQL
Web Development

How to Search Custom or Composite Columns in Laravel DataTables

8 Min Read
Login to Laravel programmatically without a password (Auth::login and loginUsingId)
Web Development

Login to Laravel Programmatically Without a Password (Auth::login & loginUsingId)

4 Min Read
Convert an image to a base64 data URL in JavaScript
Web Development

How to Convert an Image to a Base64 String in JavaScript

5 Min Read
WordPress check if user is logged in with is_user_logged_in()
Web Development

How to Check If a User Is Logged In in WordPress

7 Min Read
How7oHow7o

Free browser-based tools, prank screens, and step-by-step tech tutorials. No signup, nothing uploaded.

  • Private by design — your files never leave your device
  • Instant — no signup, no install, no waiting
  • Always free — no trials, no watermarks, no paywalls

Tools

  • PDF Editor
  • Image Upscaler
  • JPEG Compressor
  • Password Generator
  • QR Code Generator
  • Video Trimmer
  • See all tools →

Pranks

  • Cracked Screen Prank
  • Fake Blue Screen (BSOD)
  • Fake Console Update Screen
  • Fake Disk Format
  • Fake Low Battery
  • Fake Virus Scan
  • See all prank screens →

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service
  • Sitemap
© 2024–2026 How7o. All rights reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?