JS being one of the most dominant programming languages on planet, has no buit-in functionality for trimming prefix & suffix from a strings, and people have to implement their own complicated, slow, bug prone implementations, ranging from using dynamic regex, to messy string manipulation approaches, only to do a basic trim operation, in fact it is surprising that no one has tried to add this functionality to the language before, maybe they did but no one really bothered to go through a four-staged proposal to request this basic feature.
Unless there's already a highly optimized, clean and widely accepted approach which has minimal complexity, Javascript lacks crucially when it comes to string manipulation (particularly trimming to be specific), which is surprising rather than disappointing, considering it dominated the entire web that is full of textual data.
please consider this situation:
let Data = "000Data000"
The first thing that comes to mind after finding that there is a trim()
function provided by language is to use it like this:
let Data = "000Data000"
trimmedData = Data.trim("0")
// expected result: "Data000"
// actuall result: "000Data000"
only to find out trim removes whitespaces, and only whitespaces, this is true for , trimStart()
, and , trimEnd()
, too
this is a commonly encountered scenario where we need to remove a specific sequence of symbols from beginning(prefix) or end(suffix) of a string.
Of course we can use capabilities of language itself to resolve this and get our very much desired "Data000
".
let Data = "000Data000";
let regex = new RegExp(`^0+`);
let trimmedData = Data.replace(regex, '');
console.log(trimmedData);
// "Data000"
and a more dynamic version:
let Data = "000ddd000";
let prefixToTrim = "0";
// Dynamically create the regular expression
let regex = new RegExp(`^${prefixToTrim}+`);
let trimmedData = Data.replace(regex, '');
console.log(trimmedData);
// "ddd000"
We can't ignore that there is a lack of a proper and elegant way of doing so.