Skip to content

Instantly share code, notes, and snippets.

@aziis98
Created August 2, 2018 20:12
Show Gist options
  • Select an option

  • Save aziis98/15453e1843c47dc46f87bd68ebb20b83 to your computer and use it in GitHub Desktop.

Select an option

Save aziis98/15453e1843c47dc46f87bd68ebb20b83 to your computer and use it in GitHub Desktop.
const structuralReplace = (string, pattern, replacer) => {
if (typeof string === 'string') {
const acc = [];
let m;
let prevIndex = 0;
while (m = pattern.exec(string)) {
const beforeMatch = string.substring(prevIndex, pattern.lastIndex - m[0].length);
if (beforeMatch.length > 0) acc.push(beforeMatch);
acc.push(replacer(m));
prevIndex = pattern.lastIndex;
}
acc.push(string.substring(prevIndex));
return acc;
}
else {
// In this can the 'string' parameter must
// be an array of strings and other things.
return string.map(it => structuralReplace(it, pattern, replacer));
}
}

Structural Replace Function

The first argument of this function is a string or a list of strings (yet to parse) mixed with some already parsed objects. An example usage is the following

structuralReplace(
	'**this** is **a** test',
	/\*\*(.+?)\*\*/g,
	m => ({ style: 'bold', text: m[1] })
)

and this produces an object of the following form

[
	{ style: 'bold', text: 'this' },
	'is',
	{ style: 'bold', text: 'a' },
	'test'
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment