From 53922d35589e20d96e89a9e69fe4158477330ae9 Mon Sep 17 00:00:00 2001 From: saqimtiaz Date: Sat, 7 Nov 2020 11:09:11 +0100 Subject: [PATCH] search-replace string operator (#4973) * Added search-replace operator * Merge with master * Add try catch around new RegExp * Better error handling --- core/modules/filters/strings.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/core/modules/filters/strings.js b/core/modules/filters/strings.js index 38620454c..37bd826e8 100644 --- a/core/modules/filters/strings.js +++ b/core/modules/filters/strings.js @@ -115,4 +115,32 @@ exports.splitregexp = function(source,operator,options) { return result; }; +exports["search-replace"] = function(source,operator,options) { + var results = [], + suffixes = operator.suffixes || [], + flagSuffix = suffixes[0] || [], + flags = (flagSuffix.indexOf("g") !== -1 ? "g" : "") + (flagSuffix.indexOf("i") !== -1 ? "i" : ""), + isRegExp = (suffixes[1] && suffixes[1][0] === "regexp") ? true : false, + searchTerm, + regExp; + + source(function(tiddler,title) { + if(title && (operator.operands.length > 1)) { + //Escape regexp characters if the operand is not a regular expression + searchTerm = isRegExp ? operator.operand : $tw.utils.escapeRegExp(operator.operand); + try { + regExp = new RegExp(searchTerm,flags); + } catch(ex) { + return ["RegExp error: " + ex]; + } + results.push( + title.replace(regExp,operator.operands[1]) + ); + } else { + results.push(title); + } + }); + return results; +}; + })();