JSFiddle - React, Tailwind, and code Playground
JavaScript
function substitute (str) { 'use strict';
var substitutions = {
"Stack Overflow": "http://stackoverflow.com",
"Wikipedia": "http://en.wikipedia.org",
// ...and so on...
},
skeys = Object.keys (substitutions);
// build regexp which will capture each match separtely
return str.replace (new RegExp ('(' + skeys.join(")|(") + ')', "gi"), function (m0) {
// Now scan the arguments array (omitting the last two arugements which
// are the source string and match index
for (var ai, i = arguments.length - 2; --i;) {
// The index of the argument (less 1) corresponds to the index in skeys of the
// name in the substitutions
if ((ai = arguments[i])) {
return '<a href="' + substitutions[skeys[i - 1]] + '">' + ai + '</a>';
}
}
return m0;
});
}
var str = "You should visit stack overflow. I found it on Wikipedia.";
// check in console log that links are correctly built.
console.log (substitute (str));
document.write (substitute (str));