Slightly improve the performance of removeNullCharacters

Most of the strings shouldn't contain special chars (<= 0x1F) so we can
have a fast path which just checks if the string contains at least one such
a char.
This commit is contained in:
Calixte Denizet 2023-10-24 23:10:08 +02:00
parent 3f2072eaee
commit 651057c039

View File

@ -206,19 +206,20 @@ function parseQueryString(query) {
return params; return params;
} }
const InvisibleCharactersRegExp = /[\x01-\x1F]/g; const InvisibleCharactersRegExp = /[\x00-\x1F]/g;
/** /**
* @param {string} str * @param {string} str
* @param {boolean} [replaceInvisible] * @param {boolean} [replaceInvisible]
*/ */
function removeNullCharacters(str, replaceInvisible = false) { function removeNullCharacters(str, replaceInvisible = false) {
if (typeof str !== "string") { if (!InvisibleCharactersRegExp.test(str)) {
console.error(`The argument must be a string.`);
return str; return str;
} }
if (replaceInvisible) { if (replaceInvisible) {
str = str.replaceAll(InvisibleCharactersRegExp, " "); return str.replaceAll(InvisibleCharactersRegExp, m => {
return m === "\x00" ? "" : " ";
});
} }
return str.replaceAll("\x00", ""); return str.replaceAll("\x00", "");
} }