Skip to content

Instantly share code, notes, and snippets.

@georgepsarakis
Last active December 25, 2015 06:29
Show Gist options
  • Save georgepsarakis/6932942 to your computer and use it in GitHub Desktop.
Save georgepsarakis/6932942 to your computer and use it in GitHub Desktop.
JS String methods
String.prototype.sub = function(regex, replacement){
var s = this.toString();
var matches = s.match(regex);
if ( matches !== null ){
for(i in matches){
var item = matches[i];
if ( !item.escaped() ){
s = s.replace(item, replacement);
}
}
}
return s;
}
String.prototype.escaped = function(){
return ( this.toString().match(/^%{2,}/) !== null );
}
String.prototype.format = function (params){
var s = this.toString();
for(var k in params){
var re = new RegExp("[%]+\\(" + k + "\\)s", 'g');
s = s.sub(re, params[k]);
}
return s;
}
String.prototype.html_encode = function(){
return this.toString().replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&apos;");
}
String.prototype.html_decode = function () {
return $('<div/>').html(this.toString()).text();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment