The String.indexOf Second Argument in JavaScript
Using indexOf is a very common operation in Javascript. Though a little known feature is that indexOf can start searching from any point in a string. At first, this seems like a feature purely for performance optimization. But it useful when doing more complex cases of string parsing.
The following replaces all content between 2 tags (containing anything) within a string with another string:
function replaceTaggedContent(contentString, repeaterTag, replaceWith) { let newString = contentString; let index = 0; while (index < contentString.length) { const startIndex = newString.indexOf(repeaterTag, index); // No point in continuing, there is nothing more to replace. if (startIndex < 0) { break; } // No point in continuing, there is no second string to match. const endIndex = newString.indexOf(repeaterTag, startIndex + repeaterTag.length); if (endIndex < 0) { break; } const endPoint = endIndex + repeaterTag.length; newString = newString.substring(0, startIndex) + replaceWith + newString.substring(endPoint); index = startIndex + replaceWith.length; } return newString; } const result = replaceTaggedContent( 'BEFORE-@should replace@-MIDDLE-@should-replace@-AFTER' , '@', 'REPLACED'); console.log('After :', result); // BEFORE-REPLACED-MIDDLE-REPLACED-AFTER
Arguably, this can be done with regex though at that point the tags would need to be escaped and the expression would look quite complicated. This is also relatively easy to upgrade to other scenarios like supporting replacing a list of words corresponding to the index of the current replacement.
Github Location https://github.com/Jacob-Friesen/obscurejs/blob/master/2018/taggedStringReplace.js












