String.prototype.left=function(length){
// Usage: newString=myString.left(2);
// Return the left part of the string with the given length.
return this.substring(0,length);
}
String.prototype.right=function(length){
// Usage: newString=myString.left(2);
// Return the right part of the string with the given length.
return this.substring(this.length-length);
}
String.prototype.isValidEmail = function(){
// Usage: myBoolean=myString.isValidEmail();
// Returns true if the string is a valid email address.
// return !!this.match(/^[a-zA-Z0-9]+([\.\-\_]{1}[a-zA-Z0-9]+)*\@[a-zA-Z0-9]+([\.\-\_]{1}[a-zA-Z0-9]+)*\.([a-zA-Z]{2,4})$/)
return !!this.match(/^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/);
}
String.prototype.trimLeft = function(){
// Usage: newString=myString.trimLeft();
// Removes leading whitespaces from the current string and returns it.
return this.replace(/^\s+/,"");
}
String.prototype.rightTrim = function(){
// Usage: newString=myString.rightTrim();
// Removes ending whitespaces from the current string and returns it.
return this.replace(/\s+$/,"");
}
String.prototype.trim = function(){
// Usage: newString=myString.trim();
// Removes leading and ending whitespaces from the current string and returns it.
return this.replace(/(^\s+)|(\s+$)/g,"");
}
String.prototype.htmlEscape = function(){
// Usage: newString=myString.htmlEscape();
// Returns a html-escaped version of the current string.
var e=""; for(var n=0;n<this.length;n++){ var c=this.substring(n,n+1); e+=(c.match(/[a-z0-9]/i))?c:"&#"+this.charCodeAt(n)+";"; }
return e;
}
String.prototype.uriEscape = function(mode){
// Usage: newString=myString.uriEscape('url');
// Returns a uri-escaped version of the current string. Use the optional mode "url" for escaping a URL or leave empty for escaping params.
return (mode=='url')?encodeURI(this):encodeURIComponent(this);
}
Kommentar
Lite allmänna string prototypes som kan vara bra att ha.