Skip to content

Latest commit

 

History

History
31 lines (27 loc) · 1.15 KB

Removing space in string in Javascript.md

File metadata and controls

31 lines (27 loc) · 1.15 KB

Убираем пробелы

Если мы хотим убрать все пробелы из строки, то мы можем использовать replace вместе с рег-ми выражениями

var name = "ITMO University  ";
name.replace(/\s/g,''); // ITMOUniversity
\s --> space
g --> replace globally
We can also replace the space with '-'
var name = "Javascript jeep  ";
name.replace(/\s/g,'-'); // ITMO-University--

Если мы хотим удалить пробелы с одной из сторон, то можем вызывать методы trimRight и trimLeft

var s = "string   ";
s = s.trimRight();    // "string"
//trimRight() returns a new string, removing the space on end of the string
If you want to remove the extra space at the beginning of the string then you can use
var s = "    string";
s = s.trimLeft();    // "string"

//trimLeft() returns a new string, removing the space on start of the string

И с обоих сторон с помощью trim

var s = "   string   ";
s = s.trim();    // "string"

//trim() returns a new string, removing the space on start and end of the string