Удалить все пробелы из строки в JavaScript
В этом посте мы обсудим, как удалить все пробельные символы из строки в JavaScript.
Решение должно удалить из строки все символы новой строки, символы табуляции, пробелы или любые другие пробельные символы.
1. Использование регулярных выражений
Нет собственного метода JavaScript replaceAll() , который заменяет все экземпляры символа заменой. Общая стратегия замены шаблона в заданной строке заключается в использовании replace() метод, который может принимать RegExp объект.
Вот рабочий пример, который заменяет все пробелы в строке пустой строкой (включая начальные, конечные и несколько последовательных пробелов). g переключатель в регулярном выражении выполняет поиск и замену по всей строке.
как убрать пробелы в строке js

Для удаления пробелов только в начале и в конце строки существует метод trim() :
Если же надо удалить вообще все пробелы, можно воспользоваться методом replaceAll() , передав ему первым аргументом пробел ' ' , а вторым — пустую строку '' :
String.prototype.trim()
The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string.
To return a new string with whitespace trimmed from just one end, use trimStart() or trimEnd() .
Try it
Syntax
Return value
A new string representing str stripped of whitespace from both its beginning and end. Whitespace is defined as white space characters plus line terminators.
If neither the beginning or end of str has any whitespace, a new string is still returned (essentially a copy of str ).
Remove whitespaces inside a string in javascript
I’ve read this question about javascript trim, with a regex answer.
Then I expect trim to remove the inner space between Hello and World.
EDITED
Why I expected that!?
Nonsense! Obviously trim doesn’t remove inner spaces!, only leading and trailing ones, that’s how trim works, then this was a very wrong question, my apologies.
7 Answers 7
For space-character removal use
for all white space use the suggestion by Rocket in the comments below!
trim() only removes trailing spaces on the string (first and last on the chain). In this case this regExp is faster because you can remove one or more spaces at the same time.
If you change the replacement empty string to ‘$’, the difference becomes much clearer:
Performance comparison — /\s+/g is faster. See here: http://jsperf.com/s-vs-s
Update
You can use too:
![]()
Probably because you forgot to implement the solution in the accepted answer. That’s the code that makes trim() work.
update
This answer only applies to older browsers. Newer browsers apparently support trim() natively.
The best way is to do it this way if you only want to replace the whitespaces:
I used str.replace(/\s/g, ""); a lot but it does not work in all the browsers for example it does not work in duckduckgo in android and also it does not work in android webview.
You can use Strings replace method with a regular expression.
«Hello World «.replace(/ /g, «»);
The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp
/ / — Regular expression matching spaces
g — Global flag; find all matches rather than stopping after the first match
![]()
You could use a recursive solution:
![]()
Precise answer to how to approach this depends on precise intention. To remove any and/or all white space characters you should use:
‘s t r i n g’.replace(\s+\g, »)
If the intention is to only remove specific types of whitespaces (ie. thin or hair spaces) they have to be listed explicitely like this:
‘s t r i n g’.replace(\ |\t \g, »)
However if the intention is to remove just plain spaces only, then performance wise the best solution is: