SO-66788562
by David Thomas
JavaScript
// a sample of Strings and their corresponding replacement-arrays:
let string1 = "my {cat} has {2} ears",
arr1 = ["dog", "4"],
string2 = "They call me ~Ishmael~",
arr2 = ['Susan'],
string3 = "It is a #@truth@# #@universally acknowledged@#...",
arr3 = ['questionable assertion', 'oft cited'];
// here we use a named Arrow function which takes three arguments:
// haystack: String, the string which features the words/characters to
// be replaced,
// needles: Array of Strings with which to replace the identified
// groups in the 'haystack',
// Array of Strings, these strings represent the characters with
// which the words/characters to be replaced may be identified;
// the first String (index 0) is the character marking the begining
// of the capture group, and the second (index 1) indicates the
// end of the captured group; this is supplied with the default
// curly-braces:
const replaceWords = (haystack, needles, delimiterPair = ['{', '}']) => {
// we use destructuring assignment, to assign the string at
// index 0 to the 'start' variable, the string at index 1 to
// the 'end' variable; if no argument is provided the default
// curly-braces are used/assigned:
const [start, end] = delimiterPair,
// here we construct a regular expression, using a template
// string which interpolates the variables within the string;
// the regular expression is composed of:
// 'start' (eg: '{')
// .+ : any character that appears one or more times,
// ? : lazy quantifier so the expression matches the
// shortest possible string,
// 'end' (eg: '}'),
// matched with the 'g' (global) flag to replace all
// matches within the supplied string.
// this gives a regular expression of: /{.+?}/g
regexp = new RegExp(`${start}.+?${end}`, 'g')
// here we compose a String using the template literal, to
// interpolate the 'haystack' variable and also a tab-character
// concatenated with the result returned by String.prototype.replace()
// we use...