How do I remove all whitespace from a string? I can think of some obvious methods such as looping over the string and removing each whitespace character, or using regular expressions, but these solutions are not that expressive or efficient. What is a simple and efficient way to remove all whitespace from a string?
The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".
JavaScript String trim() The trim() method removes whitespace from both sides of a string. The trim() method does not change the original string.
Use the replace() method to remove all whitespace from a string in TypeScript, e.g. str. replace(/\s/g, '') . The replace method takes a regular expression and a replacement string as parameters. The method will return a new string with all whitespace removed.
If you want to modify the String
, use retain
. This is likely the fastest way when available.
fn remove_whitespace(s: &mut String) { s.retain(|c| !c.is_whitespace()); }
If you cannot modify it because you still need it or only have a &str
, then you can use filter and create a new String
. This will, of course, have to allocate to make the String
.
fn remove_whitespace(s: &str) -> String { s.chars().filter(|c| !c.is_whitespace()).collect() }
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