search-replace string operator (#4973)

* Added search-replace operator

* Merge with master

* Add try catch around new RegExp

* Better error handling
optimising-macrocalls
saqimtiaz 2020-11-07 11:09:11 +01:00 zatwierdzone przez GitHub
rodzic c41e34793d
commit 53922d3558
Nie znaleziono w bazie danych klucza dla tego podpisu
ID klucza GPG: 4AEE18F83AFDEB23
1 zmienionych plików z 28 dodań i 0 usunięć

Wyświetl plik

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