Convert Text Cases using jQuery, without CSS
You may want to convert the 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
For sentence case, the first letter of the first word is capitalized in the sentence or heading.
$('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
For title case, the first letter of each word is capitalized in the sentence or the heading.
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.
The modified string is then returned.
5. To Pascal case
For PascalCase, the first letter of each concatenated word is capitalized. 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();
});new_str = new_str.replace(/\s/g, '');
$('.list-title').text(new_str) // str = 'Mac-bookPro'
It is same as title case. Just the spaces are removed and the string is obtained.
or assign the CSS property of text-transform
$('selector').css('text-transform', 'capitalize')
Changing text case made easy ;)