Skip to content

Instantly share code, notes, and snippets.

@MattiSG
Created January 15, 2013 16:03
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 MattiSG/4539703 to your computer and use it in GitHub Desktop.
Save MattiSG/4539703 to your computer and use it in GitHub Desktop.
Wraps a substring of a string with the given prefix and suffix, ignoring case for finding while still respecting it in the resulting string.
/** Wraps a substring with the given prefix and suffix in a string.
*
*@param {String} hay The string in which the replacement is to occur.
*@param {String} needle The string to look for. Will be wrapped without case sensitivity, but will respect the case of the original string.
@param {String} prefix The string to insert before `needle`.
@param {String} suffix The string to insert after `needle`.
*/
function wrap(hay, needle, prefix, suffix) {
var lowHay = hay.toLowerCase(),
lowNeedle = needle.toLowerCase(),
index = lowHay.indexOf(lowNeedle);
if (index <= -1)
return hay;
return hay.slice(0, index)
+ prefix
+ hay.slice(index, index + needle.length)
+ suffix
+ hay.slice(index + needle.length);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment