Skip to content

Instantly share code, notes, and snippets.

@phocks
Created April 29, 2019 01:59
Show Gist options
  • Save phocks/94e76d04113fc4b3b867763d23d375f9 to your computer and use it in GitHub Desktop.
Save phocks/94e76d04113fc4b3b867763d23d375f9 to your computer and use it in GitHub Desktop.
// Set up dynamic portals
// In Core we accept #DYNAMICtrueSEARCH1987REPLACEbirthyear
// And it searches for "1987" then surrounds it in a span tag classed "birthyear"
if (props.config.dynamic) {
const unspacedTextToReplace = props.config.search + '';
const textToReplace = unspacedTextToReplace ? replaceAll(unspacedTextToReplace, '1s', ' ') : '';
const regexReplace = new RegExp(`\\s${textToReplace}\\s`, 'i');
const nameOfReplaceClass = props.config.replace;
props.nodes.forEach(node => {
const currentText = node.innerHTML;
const foundText = currentText.match(regexReplace);
if (foundText) {
const modifiedText = currentText.replace(
regexReplace,
` <span class="${nameOfReplaceClass}">${foundText[0].trim()}</span> `
);
node.innerHTML = modifiedText;
}
});
}
function escapeRegExp(str) {
return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
}
function replaceAll(str, find, replace) {
return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment