Custom JavaScript String Functions

I’ve created some missing native JavaScript String function to trim, convert to camel case, to underscored and to dashed formats.

Here is the trim() function (gist page):

/**
 * trim: removes leading and trailing white space
 */
String.prototype.trim = function () {
	return this.replace(/^\s+|\s+$/g, "");
};

And the toCamelCase() function (gist page):

/**
 * toCamelCase: converts string to camel case
 */
String.prototype.toCameCase = function () {
	return this.replace(/^\s+|\s+$/g, "")
		.toLowerCase()
		.replace(/(\s[a-z0-9])/g, function ($1) {
			return $1.replace(/\s/, '').toUpperCase();
		})
		.replace(/\W/g, '');
};

And the toDashed() function (gist page):

/**
 * toDashed: converts string to dashed
 */
String.prototype.toDashed = function () {
	return this.replace(/^\s+|\s+$/g, "")
	.toLowerCase()
	.replace(/-/g, '')
	.replace(/(\s[a-z0-9])/g, function ($1) {
		return $1.replace(/\s/, '-');
	})
	.replace(/[^a-z0-9-]/g, '');
};

And finally, the toUnderscored() function (gist page):

/**
 * toUnderscored: converts string to underscored
 */
String.prototype.toUnderscored = function () {
	return this.replace(/^\s+|\s+$/g, "")
	.toLowerCase()
	.replace(/_/g, '')
	.replace(/(\s[a-z0-9])/g, function ($1) {
		return $1.replace(/\s/, '_');
	})
	.replace(/[^a-z0-9_]/g, '');
};
This entry was posted in JavaScript, Tech and tagged , , , . Bookmark the permalink.

Comments are closed.