Skip to content

Instantly share code, notes, and snippets.

@krosenberg
Last active August 29, 2015 14:13
Show Gist options
  • Save krosenberg/ce977bac0accb703c255 to your computer and use it in GitHub Desktop.
Save krosenberg/ce977bac0accb703c255 to your computer and use it in GitHub Desktop.
Wrap RegEx matches in a string with html tags (or anything)
var TagAdder = (function(regExp, openTag, closeTag) {
var regExp = regExp || /(?:)/gi;
var openTag = openTag || '<span class="highlighted">';
var closeTag = closeTag || '</span>';
function spliceSlice(str, index, count, add) {
return str.slice(0, index) + (add || "") + str.slice(index + count);
}
return {
setRegExp: function(newRegExp) {
regExp = newRegExp;
return regExp;
},
createString: function(text) {
var match, matches = [];
var numMatches = text.match(regExp).length;
// put all match objects into array
// a match has the form [0: matchText, index: indexOfMatch, input: fullText]
while (numMatches--) {
match = regExp.exec(text)
// only add if the matched text has a nonzero length
if (match[0].length) {
matches.push(match);
}
}
// the sum of the character lengths of openTag and closeTag
var tagsLength = openTag.length + closeTag.length;
matches.forEach(function(m, i) {
// split text into an array of characters so Array.splice() can be used
var workingText = text;
var openIndex = m.index + i*tagsLength;
var closeIndex = openIndex + m[0].length + openTag.length;
// insert tags at calculated indicies
var workingText = spliceSlice(workingText, openIndex, 0, openTag);
var workingText = spliceSlice(workingText, closeIndex, 0, closeTag);
// update text string
text = workingText;
});
return text;
},
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment