This function loops through JavaScript nested arrays (recursively) and replaces the strings inside them:
function replaceRecur(tree, str, newStr) {
for (var i = 1; i < tree.length; i++) {
if (Array.isArray(tree[i])) {
replaceRecur(tree[i], str, newStr)
} else {
tree[i] = tree[i].replace(str, newStr)
}
}
}
Usage example:
function replaceQuotes(tree, callback) {
var str1 = /"(?=\b)/g
, str2 = /"(?!\b)/g
, newStr1 = '“'
, newStr2 = '”'
replaceRecur(tree, str1, newStr1)
replaceRecur(tree, str2, newStr2)
callback(null, tree)
}
How should I modify replaceRecur so I allow two values per argument?
Example:
function replaceQuotes(tree, callback) {
var str = ['/"(?=\b)/g/', '"(?!\b)/g']
, newStr = '“ ”' // not sure whether to use arrays or strings
// what's more common?
replaceRecur(tree, str, newStr)
callback(null, tree)
}
(The reason is, I don't want to repeat replaceRecur, str, and newStr twice. I want to keep the code DRY.)
EDIT:
Example input (just in case):
[ 'markdown',
[ 'para', '“a paragraph”' ],
[ 'hr' ],
[ 'para', '\'another paragraph\'' ],
[ 'para', 'test--test' ],
[ 'para', 'test---test' ],
[ 'bulletlist',
[ 'listitem', '“a list item”' ],
[ 'listitem', '“another list item”' ] ] ]
replaceQuotes.