Javascript String Utilities
An implementation of some basic string transformation functions.
by Ragdata
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<div class="panel panel-default">
<div class="panel-heading"><h3 class="panel-title">Basic String Transformations in Javascript</h3></div>
<div class="panel-body center">
A demonstration of some string transformation functions written in pure Javascript.
</div>
<table class="table table-striped">
<thead>
<tr>
<th>Expressions</th>
<th class="center" style="width: 25%;">Result</th>
</tr>
</thead>
<tbody id="tablebody">
</tbody>
</table>
</div>
CSS
.center { text-align: center; }
JavaScript
/**
* Capitalise the first letter of each word in a string
*
* @returns {string}
*/
String.prototype.ucwords = function(){ return this.replace( /\w+/g, function( str ){ return str.charAt( 0 ).toUpperCase() + str.slice( 1 ).toLowerCase(); } ); };
/**
* Capitalise the first letter of a string
*
* @returns {string}
*/
String.prototype.ucfirst = function(){ return this.charAt( 0 ).toUpperCase() + this.slice( 1 ).toLowerCase(); };
/**
* Pluralise a string
*
* @param items integer [optional - defaults to 0]
* @param suffix string [optional - defaults to 's']
* @param offset integer [optional - would normally be a negative integer]
*
* @returns {string}
*/
String.prototype.plural = function( items, suffix, offset )
{
items = ( typeof items !== 'undefined' ) ? items : 0 ;
suffix = ( typeof suffix !== 'undefined' ) ? suffix : 's' ;
offset = ( typeof offset !== 'undefined' ) ? offset : 0 ;
if( items == 0 || items > 1 )
{
if( offset == 0 )
{
return this + suffix;
}
else
{
return this.slice( 0, offset ) + suffix;
}
}
return this;
};
/**
* String prototype alias for lpad()
*
* @param size integer [optional - defaults to 1]
* @param char mixed [optional - defaults to '0']
*
* @returns {*|string}
*/
String.prototype.lpad = function( size, char ){ return lpad( this, size, char ); };
/**
* String prototype alias for number_format()
*
* @param prec integer [optional - defaults to 0]
* @param dec string [optional - defaults to '.']
* @param sep string [optional - defaults to ',']
*
* @returns {string}
*/
String.prototype.number_format = function( prec, dec, sep ){ return number_format( this, prec, dec, sep ); };
/**
* Left-Pad a string ... built with zero-padding numbers in mind
*
* @param string mixed
* @param size integer [optional - defaults to 1]
* @param char ...