JavaScript Equivalent of PHP’s ucwords Function

The JavaScript function below performs the equivalent of PHP’s strtolower and then ucwords function combined on the text inside a given text input element. It’s straight JavaScript and doesn’t require jQuery.

It works by converting the entire string to lowercase, then breaking apart the words into an array, capitalizing the first letter of each word, then combining the words back into a string and returning them to the text input field.

You can see it in action here:

Here’s the function:

function ucwords(id) {
	var str = document.getElementById(id).value;
	str = str.toLowerCase();
	var words = str.split(' ');
	str = '';
	for (var i = 0; i < words.length; i++) {
		var word = words[i];
		word = word.charAt(0).toUpperCase() + word.slice(1);
		if (i > 0) { str = str + ' '; }
		str = str + word;
	document.getElementById(id).value = str;

To use it, simply copy and paste into a JavaScript file or in between <script> tags on your page, then feed it the ID of your text input field like this:

<input type="text" id="text_input"> 
<input type="button" value="Adjust Case" onclick="ucwords('text_input');">



This article was published on January 6th, 2018 by Robert James Reese in the JavaScript category. Before using any of the code or other content in this post, you must read and agree to our terms of use.