Categories
Tutorials

Title Capitalization with JavaScript

JavaScript, JS, is an amazing scripting language and it’s been adopted by many platforms including Node.js, which turns JS into a server side scripting language. You can even program a PDF form using Adobe® Acrobat JS API. Very versatile and powerful scripting language.

JavaScript, JS, is an amazing scripting language and it’s been adopted by many platforms including Node.js, which turns JS into a server side scripting language. You can even program a PDF form using Adobe® Acrobat JS API. Very versatile and powerful scripting language.

But, as any other scripting language, there some functionalities that you will miss from languages that you might be using today. In my case, PHP.

An example of the many functions I use a lot with PHP is the function ucwords() which stands for Upper Case Words (Capitalize each word on a string provided).

The ucwords() function is used as follow:

<?php echo ucwords('hello world'); ?>

This will print:

Hello World

With JavaScript, the only functions equivalent to this is String.prototype.toUpperCase() and String.prototype.toLowerCase(), but also has this very useful string function String.prototype.toLocaleUpperCase() which will capitalize the entire string maintaining it’s locale language expressions.

The problem with these functions is that they upper/lower case the entire string, But if you want to do a title case version as PHP’s ucwords(), you need to create your own String.prototype function. Many feel tempted to use Regular Expressions for this, but that’s a totally over-kill process since it takes extra milliseconds for JS to process this.

You can still use the string functions provided by JS to return the same results, but you need to combine other available functions to recreate it or even enhance this functionality.

If you are a beginner interested in learning JavaScript step by step follow along this tutorial, if you already know what you are doing you can view the final code here. Or at the end of this tutorial.

Rafael Vila

String.prototype.split()

The String.prototype.split() function is your first step in order to create an array list for each word provided in a string statement. For this example I will create a variable called 'stringVar' with the string value "JavaScript title case function".

'use strict';
var stringVar = 'JavaScript title case function';

Open your favorite text editor and follow through with this tutorial. If you have never used JS before, this will help you get started. Save the file as 'titleCase.js', if you are on Windows, I recommend to use Visual Studio Code, Brakets or NotePad++ over Windows’ own NotePad, believe me, makes things easier. But my top choice is Visual Studio Code.

Since we need to capitalize each word stored on the stringVar variable, we need to split it into an array using the split() function like this:

var stringArray = stringVar.split(' ');

As you can see, when splitting the string value, you need to specify String.prototype.split() to do the split using each blank space as reference, if you do not specify, the string will be split letter by letter, which is useful for other stuff, but not for what we are trying to do. You can specify to split by any character, just FYI.

Now is where the fun part start, we need to ask JS to look each iteration on the new array we created… Wait what, what are you talking about? Yeah, I forgot to tell you, that’s why I called this new variable stringArray because is what it is, the split function turn the string stored on stringVar into an array that should look like this when sent to the console:

console.log(stringArray);
//output
["JavaScript","title","case","function"]

You won’t find an item with the blank spaces because that was the delimiter for the split. Since is an array, we can use a loop function to accomplish our goal, in our case we are going to use the for loop.

The For Loop

for (i in stringArray) {
    if (stringArray.hasOwnProperty(i)) {
       ...
    }
}

The above code what it does is to assign the item key as a numeric value to a new declared variable i which stands for item, you can call the variable whatever you like and what makes sense to you.

Array.prototype.hasOwnProperty()

Inside the for loop you noticed I created an if statement that will only be executed if the key item is found on the array properties. One thing you need to be aware of is that objects in JS not only contain the items you are storing on them, but also will include properties that are used by JS to properly interact with the object. I will not going to explain this deep down into details, but you can test it on your browser’s developer mode console by entering:

console.log(['hello','world']);

There are many ways you can accomplish our goal, but I prefer this one which is similar to another PHP function I use very often called foreach, which I love by the way. I will declare a new variable called jointString where we are going to stored each iteration of the stringArray capitalized. For that I’m going to use another JS array function called Array.prototype.push().

Array.prototype.push()

var jointString = [];

for (i in stringArray) {
    if (stringArray.hasOwnProperty(i)) {
       jointString.push(...);
    }
}

The push() function is the equivalent to PHP’s array_push() but it is a lot cleaner to use, and what it those is to add an item to an existing array. Since our array is empty:

var jointString = [];
//same as
//var jointString = new Array();

We are going to add an item by pushing it into jointString array during our for loop. But before we delve into that, let’s talk about what we are going to push in the array, and for that I’m going to introduce a new JS String function String.prototype.substring().

String.prototype.substring()

The substring() function what it does is to select a portion from a given string and two parameters have to provide where to start and where to end. For example, let’s say I want to grab the first three letters of a string "FooBar":

var foobar = "FooBar",
    foo = foobar.substr(0,3),
    bar = foobar.substr(3,6);

console.log(foobar, foo, bar);

//Output
FooBar
Foo
Bar

As you can see, when dealing with scripting language you have to set your mind that counting starts on 0, not 1. "FooBar" string has a length of 6, but it is counted as 0, 1, 2, 3, 4 and 5.

In our first attempt we are telling substring() to store partial part of the string “FooBar” from 0 to 3, which is telling from start to the third letter (0,1,2) (F,o,o) then store this new partial value into a new declared variable called foo.

Now, for the second attempt we are telling substring() to start from the third letter forward, and since we know the length of our string we can be specific, we asked to continue until the sixth letter (3,4,5) (B,a,r), then store this partial value into a new declared variable called bar.

The last step is OK, if you know the length for the string given, but in the real world, we have words that has different length, and for this you need to think fluid. Let revisit the code in a more realistic scenario:

var foobar = "FooBar",
    foo = foobar.substr(0,3),
    bar = foobar.substr(3,foobar.length);

console.log(foobar, foo, bar);

//Output
FooBar
Foo
Bar

Above you noticed the code stayed almost the same with the exception on how we implement the bar variable request. This time we were not specific but implement the execution of the String.prototype.length property.

String.prototype.length

The length() property works with either Array/Objects or Strings, but they are implemented differently, in our case with are using the function for a string value. This function what it does is to return the numeric total of characters in a string. For our previous example the value is 6.

Notice in this case the value is exactly what you expect it to be, since this in not counting steps as items in an array that start counting from 0. For length() the zero value represent an empty string.

Important Note: This property returns the number of code units in the string. UTF-16, the string format used by JavaScript, uses a single 16-bit code unit to represent the most common characters, but needs to use two code units for less commonly-used characters, so it’s possible for the value returned by length to not match the actual number of characters in the string.

MDN Web Docs

Putting Stuff Together

Now let’s start putting things together:

'use strict';
var stringVar = 'JavaScript title case function',
    stringArray = stringVar.split(''),
    jointString = [],
    i,
    tempString,
    newString;

//capitalizing each word and pushing value into
//the jointString array
for (i in stringArray) {
    if (stringArray.hasOwnProperty(i)) {
       tempString = stringArray[i].substring(0,1)
          .toLocaleUpperCase()
          + stringArray[i]
          .substring(1,stringArray[i].length);
          jointString.push(tempString);
    }
}

Don’t panic, I will explain …

Since I’m declaring at the very beginning of the code that I want this to be an strict code 'use strict'; I have to declare all variable I’m using, and I’m doing that right below the 'use strict'; statement.

I added a couple of new variable which will be used inside the for loop statement: iand tempString. The later will hold the string to be pushed into the jointString array.

Inside the for loop statement is where things have the appearance of complication but it is not, let break it apart.

First we declare the for loop as I explained before and make sure that it is using the properties we are requiring. Then we are requesting the single current item value as follow:

stringArray[i]

As you noticed that we asked the for loop to hold the key numeric value of each item in the variable i, which we then using to specify which item we are requesting the value from, for example, stringVar variable is storing a sentence with a total of 4 words, which are now stored as and array in the stringArray variable, and this can be represented as follow [key: value], see below:

[1: "Javascript", 2: "title", 3: "case", 4: "function"]

But remember that keys in an array starts at 0, same principle when specifying starting and end point to the substring() function, and this is true in all computer languages that I know of:

[0: "Javascript", 1: "title", 2: "case", 3: "function"]

When the loop statement interact with each item you need to specify which to get the value from by specifying the key, let’s say I want to the get the fourth word, to do that I need to request this value as follow:

stringArray[3]

//example:
console.log(stringArray[3]);
//output
function

Understanding this principle let’s give tempString variable a value:

tempString = stringArray[3].substring(0,1).toLocaleUpperCase();
tempString += stringArray[3].substring(1, stringArray[3].length);

We can make this more visually pleasing as follow, this is note necessary, but I will do it for the sake of this tutorial and easy step by step explanation:

var itemValue = stringArray[3],
    finalPosition = itemValue.length,
    firstLetter = itemValue.substring(0,1),
    restOf = itemValue.substring(1, finalPosition);

tempString = firstLetter.toLocaleUpperCase() + restOf;

In the above code we assign each new variable declared a independent purpose which is easier to read than the two liner version, first we assign the value of an specific item into itemValue variable.

itemValue = stringArray[3];

Next we look for the final position (counting from 0 to end):

finalPosition = itemValue.length;

After this, we requested the first letter of the string and assigned it to the firstLetter variable:

firstLetter = itemValue.substring(0,1);

Then we stored the rest of the string in restOf variable starting from position 1 (second letter) to the last letter position stored in finalPosition variable:

restOf = itemValue.substring(1, finalPosition);

After this is done, then we can concatenate the final values and assigned it to the tempString variable:

tempString = firstLetter.toLocaleUpperCase() + restOf;

In JS, to concatenate string you simple use the + sign same as Visual Basic, note that if the values are number the result will be the addition of both values.

Finishing the Code

As I said, the previous steps are not necessary, but you can keep them and apply it to the code we are working on. But I will keep this simple, it looks confusing in these small boxes, but you get used to it as you get deeper into learning the code.

'use strict';
var stringVar = 'JavaScript title case function',
    stringArray = stringVar.split(''),
    jointString = [],
    i,
    tempString,
    newString;

//capitalizing each word and pushing value into
//the jointString array
for (i in stringArray) {
    if (stringArray.hasOwnProperty(i)) {
       tempString = stringArray[i].substring(0,1)
          .toLocaleUpperCase()
          + stringArray[i]
          .substring(1,stringArray[i].length);
          jointString.push(tempString);
    }
}

newString = (jointString.length > 0)
? jointString.join(' ')
: stringVar;

console.log(stringVar, newString);

Now we are adding a new variable newString, a new array property Array.prototype.length and a new array function Array.prototype.join() into the code. And also we are introducing a the if/else statement shorthand.

Array.prototype.length

The Array.prototype.length is similar but is not the same as it’s string counterpart. In a string it returns the total value of characters in a string, while on an array it returns the total number of items in it.

Array.prototype.join()

This function will concatenate all items in an array into a string. This does the opposite that String.prototype.split() does. The later turn a string into an array, while join() turns an array into a string. As with the split() function, you need to specify what to implement between each item or separator string.

newString = jointString.join(' ');
//sending to console
console.log(newString);
//output
JavaScript Title Case Function

newString = jointString.join('-');
console.log(newString);
//output
JavaScript-Title-Case-Function

In the example above I processed the array with two different separator strings.

Since we added an if statement inside the loop, there’s might be a slight possibility that the array jointString stays empty, and to avoid user’s frustration we need to prepare the code to return at least the original value. That is why we are using the if/else shorthand.

If/Else Shorthand

To process the final value we can do something like this:

if (jointString.length > 0) {
    ...
} else {
    ...
}

Which is the traditional way to declare an if/else statement. But if it is a basic statement, the shorthand come in handy:

newString = (jointString.length > 0) ? ... : ... ;

This is basically the same thing but many scripting languages as PHP and many others offer this shorthand to help you keep your code clean and simple. Let see a comparison:

if (jointString.length > 0) {
    newString = jointString.join('');
} else {
    newstring = stringVar;
}

//shorthand
newString = (jointString.length > 0)
             ? jointString.join(' ')
             : stringVar ;

The Final Code

'use strict';
var stringVar = 'JavaScript title case function',
    stringArray = stringVar.split(''),
    jointString = [],
    i,
    tempString,
    newString;

//capitalizing each word and pushing value into
//the jointString array
for (i in stringArray) {
    if (stringArray.hasOwnProperty(i)) {
       tempString = stringArray[i].substring(0,1)
          .toLocaleUpperCase()
          + stringArray[i]
          .substring(1,stringArray[i].length);
          jointString.push(tempString);
    }
}

newString = (jointString.length > 0)
? jointString.join(' ')
: stringVar;

console.log(stringVar, newString);

After this is done and run on the browser the output should be:

JavaScript title case function
JavaScript Title Case Function 

Conclusion

In this tutorial you have learn how to create a JavaScript file, declare variables, split variable string into array, processing the variable with a for loop statement, declaring different conditions with an if statement, verifying an item exists inside and array, joining an array into a string, using if/else shorthand for a conditional outcome and a cleaner code…. uff. and that was fun.

Hope you enjoyed this tutorial as I enjoyed creating it. If you want to learn how to implement this in your first function check below.

Happy Coding, Happy Developing, see you next time.

CodePen Final Code (Real World Implementation)

See the Pen Slug to Title Simplified by Rafael (@raphievila) on CodePen.

Leave a Reply