Python's strip function is used to remove given characters from the beginning and end of the string. How to create a similar function in javascript?
Example:
str = "'^$ *# smart kitty & ''^$* '^";
newStr = str.strip(" '^$*#&");
console.log(newStr);
Output:
smart kitty
A simple but not very effective way would be to look for the characters and remove them:
function strip(str, remove) {
while (str.length > 0 && remove.indexOf(str.charAt(0)) != -1) {
str = str.substr(1);
}
while (str.length > 0 && remove.indexOf(str.charAt(str.length - 1)) != -1) {
str = str.substr(0, str.length - 1);
}
return str;
}
A more effective, but not as easy to use, would be a regular expression:
str = str.replace(/(^[ '\^\$\*#&]+)|([ '\^\$\*#&]+$)/g, '')
Note: I escaped all characters that have any special meaning in a regular expression. You need to do that for some characters, but perhaps not all the ones that I escaped here as they are used inside a set. That's mostly to point out that some characters do need escaping.
There's lodash's trim()
Removes leading and trailing whitespace or specified characters from string.
_.trim(' abc '); // → 'abc'
_.trim('-_-abc-_-', '_-'); // → 'abc'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With