Add suffix and parameter to trim operator (#4811)

* Add suffix and parameter to trim operator

Fixes #4809

* Unit tests for new trim operator parameters

* Mention trim operator in 5.1.23 release notes

* Address review comments

* Move regex escaping into utils.js trim functions

This way the trimPrefix and trimSuffix functions from utils.js are safe
to call without regex-escaping their parameters, which should make them
easier to use from other parts of the Javascript code.
This commit is contained in:
Robin Munn 2020-08-29 18:27:58 +07:00 committed by GitHub
parent ef29d05ea4
commit 5202441769
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 85 additions and 5 deletions

View file

@ -94,6 +94,36 @@ exports.trim = function(str) {
}
};
exports.trimPrefix = function(str,unwanted) {
if(typeof str === "string" && typeof unwanted === "string") {
if(unwanted === "") {
return str.replace(/^\s\s*/, '');
} else {
// Safely regexp-escape the unwanted text
unwanted = unwanted.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&');
var regex = new RegExp('^(' + unwanted + ')+');
return str.replace(regex, '');
}
} else {
return str;
}
};
exports.trimSuffix = function(str,unwanted) {
if(typeof str === "string" && typeof unwanted === "string") {
if(unwanted === "") {
return str.replace(/\s\s*$/, '');
} else {
// Safely regexp-escape the unwanted text
unwanted = unwanted.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&');
var regex = new RegExp('(' + unwanted + ')+$');
return str.replace(regex, '');
}
} else {
return str;
}
};
/*
Convert a string to sentence case (ie capitalise first letter)
*/