Here are six essential string functions to extend the functions for strings in javascript. If you are already using a major javascript framework like MooTools or Prototype, you may find many of these redundant with your javascript framework. In our case, we used YUI to develop our Trendics Control Panel and YUI didn’t include these type of string prototype functions (similar functions are available in YAHOO.lang but these are not as convenient to call)…
// Returns the string with all the beginning
// and ending whitespace removed
String.prototype.trim = function() {
return this.replace(/^\s+/, '').replace(/\s+$/, '');
};
// Returns the left x characters of the string
String.prototype.left = function(count) {
if (this.length>count) {
return this.substring(0, count);
}
else {
return this;
}
}
// Returns the right x characters of the string
String.prototype.right = function(count) {
if (this.length>count) {
return this.substring(this.length-count, this.length);
}
else {
return this;
}
}
// Returns true if the string begins with value
String.prototype.startsWith = function(value) {
if (this.length<value.length) {
return false;
}
else {
return this.substring(0, value.length)===value;
}
}
// Returns true if the string ends with value
String.prototype.endsWith = function(value) {
if (this.length<value.length) {
return false;
}
else {
return this.substring(this.length-value.length, this.length)===value;
}
}
// Returns a shortened version of the string
// suffixed with "..." if characters are truncated
// from the original string
String.prototype.shorten = function(maxLength) {
if (!this) {
result = null;
}
else if (this.length>maxLength) {
preferredSize = maxLength-'...'.length;
if (preferredSize>0) {
result = this.left(preferredSize) + '...';
}
else {
result = this.left(maxLength);
}
}
else {
result = this;
}
return result;
}
The functions above can be invoked on any javascript string like this…
alert(" Hello ".trim());
var message = "This is a longer sentence.";
alert(message.shorten(10));
Hope this helps.


Entries (RSS)