Skip to content

Instantly share code, notes, and snippets.

@westc
Last active August 29, 2015 14:05
Show Gist options
  • Save westc/39c97243080191246aac to your computer and use it in GitHub Desktop.
Save westc/39c97243080191246aac to your computer and use it in GitHub Desktop.
Surrounds the string with the specified string(s).
(function(RGX, STR, undefined) {
/**
* Surrounds the string with the specified string(s).
* @param {string} wrap1
* The string to precede this string.
* @param {string=} opt_wrap2
* The string to follow this string. Defaults to the value of `wrap1` if
* not given.
* @param {string=} opt_wrap1rep
* The string to replace all occurrences of `wrap1` within this string.
* Defaults to the value of `wrap1` if not given.
* @param {string=} opt_wrap2rep
* The string to replace all occurrences of `opt_wrap2` within this
* string. Defaults to the value of `opt_wrap1rep` if not given.
* @return {string}
* Returns this string surrounded by the wrap string(s).
*/
String.prototype.wrap = function(wrap1, opt_wrap2, opt_wrap1rep, opt_wrap2rep) {
var me = this, min, min1, min2;
opt_wrap2 = opt_wrap2 == undefined ? wrap1 : opt_wrap2;
if (arguments.length > 2) {
opt_wrap1rep = opt_wrap1rep == undefined ? wrap1 : opt_wrap1rep;
opt_wrap2rep = opt_wrap2rep == undefined ? opt_wrap1rep : opt_wrap2rep;
me = me.replace(
new RegExp('(' + wrap1.replace(RGX, STR) + ')|' + opt_wrap2.replace(RGX, STR), 'g'),
function (match, isLeft) {
return isLeft ? opt_wrap1rep : opt_wrap2rep;
}
);
}
return wrap1 + me + opt_wrap2;
};
})(/\W+/g, '\\$&');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment