Case converter in JavaScript

There are many situations in which you need to convert case of text. This post contains various snippet for case converting including Upper case, Lower case, Toggle case, Sentence case, and Proper case using JavaScript. Click here to download HTML file contains demo.

For Upper case we can simply use toUpperCase() method of string:

function upperCase(text){
	return text.toUpperCase();
}

For Lower case, same as upper case we can predefined toLowerCase() method of string:

function upperCase(text){
	return text.toLowerCase();
}

For Toogle case, we are manually checking for ascii key of character and if we find ascii of uppercase then add 32 for convert it to lowercase. and use vice versa for lowercase.

function toggleCase(text){
	var size = text.length;
	var output = "";
	for(var i = 0; i < size; i++)
	{
		var asc = text.charCodeAt(i);
		if(asc > 64 && asc < 91)
			output += String.fromCharCode(asc + 32);
		else if(asc > 96 && asc < 123)
			output += String.fromCharCode(asc - 32);
		else if(asc != 0)
			output += text.charAt(i);
	}
	return output;
}

For Proper case, we need to use regular expression.

function properCase(text){
	return text.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

For Sentence case, we need to convert text to lowercase and use regular expression on it.

function sentenceCase(text){
	text = text.toLowerCase();
	var rg = /(^\w{1}|\.\s*\w{1})/gi;
	return text.replace(rg, function(toReplace) {
		return toReplace.toUpperCase();
	});
}

Leave a Reply

Your email address will not be published. Required fields are marked *