Convert Text Cases using jQuery, without CSS

JavaScript jQuery Web Development

The data you have on your storage server can be used in various places on your website. Let’s say, you want it all uppercase when it is used on one page, and on the other, you want it in the sentence case. To do this, you are not going to have the same data in different cases on your server, rather, you should convert text case in your webpage, without wanting to modify the data in the server itself.

In this article, you will see, how to convert text value of an element, referred to as “selector” here, to lowercase, uppercase, title case and pascal case using jquery.

Let us fetch the string to be converted and have it in a variable, so we reuse it for different cases.

str = $('selector').text(); // Let's assume str = 'mac-Book pRO'

1. To Lowercase

$('selector').text(str.toLowerCase()); // str = 'mac-book pro'

2. To Uppercase

$('selector').text(str.toUpperCase()); // str = 'MAC-BOOK PRO'

3. To Sentence case

Capitalise the first letter of the first word in the sentence or heading for sentence case.

$('selector').text(str.charAt(0).toUpperCase() + str.substr(1).toLowerCase()) // str = 'Mac-book pro'

Here, str.charAt(0).toUpperCase() converts the first character of the string to uppercase.
str.substr(1) – fetches the substring from the string starting from index 1 till the end.
str.substr(1).toLowerCase() – converts the extracted sub-string to lowercase

4. To Title case

Capitalise the first letter of each word in the sentence or the heading for title case.

new_str = str.toLowerCase().replace(/\b[a-z]/g, function(txtVal) {
    return txtVal.toUpperCase();
});
$('.list-title').text(new_str) // str = 'Mac-book Pro'

str is first converted entirely to lowercase. Then, the regex  /\b[a-z]/  determines the word break and converts the 1st letter of the word to uppercase.
It then returns the modified string.

5. To Pascal case

Capitalise the first letter of each concatenated word for PascalCase. The spaces between the words are removed and no separators like a hyphen, dot etc is used.

new_str = str.toLowerCase().replace(/\b[a-z]/g, function(txtVal) {
    return txtVal.toUpperCase();
});
$('.list-title').text(new_str) // str = 'Mac-book Pro'

It is same as title case. Just remove the spaces and the obtain the string.

The other way around to achieve this is to assign the CSS property of text-transform

$('selector').css('text-transform', 'capitalize')

Changing text case made easy 😉