Skip to content

Instantly share code, notes, and snippets.

@croucha
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save croucha/87dc6db9bcbfbb161d38 to your computer and use it in GitHub Desktop.
Save croucha/87dc6db9bcbfbb161d38 to your computer and use it in GitHub Desktop.
Example of having a built in replace all utility using Regex.
(function(app) {
/*----------------------------------------------------------------------------------------------
* UTILILTY INIALIZATION
* This code is executed when the Javascript file is loaded
*--------------------------------------------------------------------------------------------*/
// Ensure util object exists
app.util = app.util || {};
// Create scoped alias to simplify references
var util = app.util;
/**
* Escapes a string for regular expression.
*
* @param {String}
* @returns {String}
*/
util.escapeRegExp = function(string) {
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
};
/**
* Replaces all occurrences found in a string.
*
* @param {String}
* @param {String}
* @param {String}
* @returns {String}
*/
util.replaceAll = function(string, find, replace) {
return string.replace(new RegExp(util.escapeRegExp(find), 'g'), replace);
};
})(app || {});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment