There's so many example in the web, about removing trailing and leading zeros. but all of them are using regex.
sample.toString().replace(/^0 /,'').replace(/0 $/,'');
is there a way to removed them without using regex? because regex is prone to ddos,
base on sonarqube.
https://rules.sonarsource.com/javascript/RSPEC-5852
CodePudding user response:
If you don't use regex, then you will have to iterate the string character by character from both ends. Actually, if you use a regex alternation it is a good and concise option:
sample.toString().replace(/^0 |0 $/g, "");
CodePudding user response:
Maybe there is a better solution, but i came with this :
const test = "0032540140043000";
const removeTrailingZeros = (str) => {
let result = `${ str}`;
while (result.at(-1) === "0") {
result = result.slice(0, -1);
}
return result;
};
console.log(removeTrailingZeros(test)); // 32540140043
Explanation : str
remove the leading "0" when parsing a string to a number, because JS prefers 123
than 0123
.
Then, a little loop to remove the trailing "0" on this string. Then, return the string.