Created
January 15, 2013 16:03
-
-
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.
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
/** 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