Created
October 15, 2015 13:08
-
-
Save lcustodio/d92cfa0fbabe79c3f422 to your computer and use it in GitHub Desktop.
String prototypes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function () { | |
'use strict'; | |
var proto = String.prototype; | |
if (undefined === proto.startsWith) { | |
/** | |
* Returns true if the string starts with the given one | |
* | |
* @param {String} str | |
* @returns {boolean} | |
*/ | |
proto.startsWith = function (str) { | |
return 0 === this.indexOf(str); | |
}; | |
} | |
if (undefined === proto.endsWith) { | |
/** | |
* Returns true if the string ends with the given one | |
* | |
* @param {String} str | |
* @returns {boolean} | |
*/ | |
proto.endsWith = function (str) { | |
var startPos = this.length - str.length; | |
return startPos === this.lastIndexOf(str); | |
}; | |
} | |
if (undefined === proto.format) { | |
/** | |
* Similar to String.Format(str, params) behavior (.Net). | |
* @returns {String} | |
*/ | |
proto.format = function () { | |
var s = this, i = arguments.length; | |
while (i--) { | |
s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]); | |
} | |
return s; | |
}; | |
} | |
if (undefined === proto.capitalize) { | |
/** | |
* Capitalize the given string | |
* | |
* @returns {String} | |
*/ | |
if (undefined === proto.toLocaleUpperCase) { | |
proto.capitalize = function () { | |
return this.charAt(0).toUpperCase() + this.substr(1); | |
}; | |
} else { | |
proto.capitalize = function () { | |
return this.charAt(0).toLocaleUpperCase() + this.substr(1); | |
}; | |
} | |
} | |
if (undefined === proto.niceReplace) { | |
/** | |
* Replace helper | |
* | |
* @param {Object} dictionary | |
* @returns {String} | |
*/ | |
/*jshint -W121 */ | |
proto.niceReplace = function (dictionary) { | |
/*jshint +W121 */ | |
var me = this; | |
for (var subStr in dictionary) { | |
if (dictionary.hasOwnProperty(subStr)) { | |
var newSubStr = dictionary[subStr]; | |
me = me.split(subStr).join(newSubStr); | |
} | |
} | |
return me; | |
}; | |
} | |
}(this)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment