1
0
mirror of https://github.com/Jermolene/TiddlyWiki5 synced 2024-11-27 03:57:21 +00:00

search-replace string operator (#4973)

* Added search-replace operator

* Merge with master

* Add try catch around new RegExp

* Better error handling
This commit is contained in:
saqimtiaz 2020-11-07 11:09:11 +01:00 committed by GitHub
parent c41e34793d
commit 53922d3558
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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;
};
})();