Remove spaces from a text or a string with JS

preview_player
Показать описание

remove spaces
in js

remove spaces at the beginning and end

To eliminate the spaces at the beginning and at the end of a text we will use the trim function, which comes by default in js

remove all spaces
method 1

with the split function we will divide the text into an array and with the join function we concatenate the array to text, thus we will eliminate all the empty spaces

remove all spaces
method 2

this is the best way to replace empty spaces

With the replace function and a regular expression, we can replace all empty spaces to another variable

with this regular expression we will search for all the empty spaces to replace them

remove all spaces and line breaks

now we will remove all characters that are considered empty space, this includes newlines and tabs

with the replace function and the following regular expression, we will remove all the empty spaces

replace multiple spaces with 1 space

If we only want to leave a space as a separation, this method will be very useful for us.

mundoby code
Рекомендации по теме
welcome to shbcf.ru