What are the different ways I can remove characters from a string in JavaScript?
To remove multiple characters from a string we can easily use the function str. replace and pass a parameter multiple characters. The String class (Str) provides a method to replace(old_str, new_str) to replace the sub-strings in a string. It replaces all the elements of the old sub-string with the new sub-string.
You can remove a character from a Python string using replace() or translate(). Both these methods replace a character or string with a given value. If an empty string is specified, the character or string you select is removed from the string without a replacement.
Use the deleteCharAt Method to Remove a Character From String in Java. The deleteCharAt() method is a member method of the StringBuilder class that can also be used to remove a character from a string in Java.
Using replace()
with regular expressions is the most flexible/powerful. It's also the only way to globally replace every instance of a search pattern in JavaScript. The non-regex variant of replace()
will only replace the first instance.
For example:
var str = "foo gar gaz"; // returns: "foo bar gaz" str.replace('g', 'b'); // returns: "foo bar baz" str = str.replace(/g/gi, 'b');
In the latter example, the trailing /gi
indicates case-insensitivity and global replacement (meaning that not just the first instance should be replaced), which is what you typically want when you're replacing in strings.
To remove characters, use an empty string as the replacement:
var str = "foo bar baz"; // returns: "foo r z" str.replace(/ba/gi, '');
ONELINER which remove characters LIST (more than one at once) - for example remove +,-, ,(,)
from telephone number:
var str = "+(48) 123-456-789".replace(/[-+()\s]/g, ''); // result: "48123456789"
We use regular expression [-+()\s]
where we put unwanted characters between [
and ]
(the "\s
" is 'space' character escape - for more info google 'character escapes in in regexp')
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