When you have a string with spaces and you try to display it in the browser, you may not get to see the spaces. So, you need to remove extra spaces. Let’s shed a light on how to remove all spaces from a string
We use a few ways to remove extra spaces from a string.
Using replaceAll Method
When you call this method, pass a string that contains a space as the first parameter and the second as an empty string
str.replaceAll(' ', ''). In return, you will get a new string with replaced matches. Take look at the code:
Using the ‘replace’ Method for Internet Explorer
const example_str2 = 'Remove All Spaces From A String Using The Replace Method For Internet Explorer'; const replaced_str2 = example_str2.replace(/ /g, ''); console.log(replaced_str2);
Here, the ‘g’ (global) flag is used to match all occurrences of the spaces and not only the first one. Apart from that, we have discussed above that the replace method never changes the original string. You will get a new string in return with one or two replaced matches.
Using replace Method with Regex
In the case, the regular expression can’t match the tabs and new lines, you need to remove all the spaces, new lines, and tabs. Check out the example
const example_str3 = 'Remove All Spaces From A String Using Replace Method With Regex'; const replaced_str3 = example_str3.replace(/\s/g, ''); console.log(replaced_str3);
Being a special character, the ‘
\s’ is used in the regex to match spaces, new lines, and tabs.
Leave a comment