It’s always helpful to have an easy method method on strings to remove trailing or leading whitespace and the trim()
method available on JavaScript strings is here to help us with doing exactly that.
在字符串上使用简单的方法方法来删除尾部或前导空格总是有帮助的,JavaScript字符串上可用的trim()
方法可以帮助我们做到这一点。
Whitespace can anything such as spaces, tabs, no-break spaces, LF (line feeds), CR (carriage returns), etc.
空格可以是诸如空格 , 制表符 , 不间断空格 , LF(换行符) , CR(回车符)等任何内容。
Let’s quickly go over how to use it.
让我们快速了解如何使用它。
String.trim() (String.trim())
The String.trim
method is used to remove the whitespace from both ends of a string.
String.trim
方法用于删除字符串两端的空格。
- Parameters: It does not accept any parameter. 参数:不接受任何参数。
- Return type: It returns the string without whitespace. 返回类型:返回不带空格的字符串。
An example of how to use it is shown below 🙈
shown的使用示例如下below
let reptilianString = " 🐊🐊🐊🐊 ";
console.log(reptilianString.trim());
// 🐊🐊🐊🐊
If we want to remove the whitespace only from the front but not from rear or vice-versa, we can also use the following methods.
如果我们只想从前面删除空白,而不是从后面删除空白,反之亦然,我们也可以使用以下方法。
trimStart()
trimStart()
trimEnd()
trimEnd()
trimStart() (trimStart())
The trimStart()
method is used to remove whitespace from the start of a string.
trimStart()
方法用于从字符串开头删除空格。
- Parameters: It does not accept any parameter. 参数:不接受任何参数。
- Return type: It returns the string without whitespace at the start. 返回类型:返回开头没有空格的字符串。
Note: trimLeft()
is an alias for trimStart()
注: trimLeft()
是一个别名trimStart()
trimEnd() (trimEnd())
The trimEnd()
method is used to remove the whitespace from the right end of the string.
trimEnd()
方法用于从字符串的右端删除空格。
Parameters: It does not accept any parameter. Return type: It returns the string without whitespace on the right end.
参数:不接受任何参数。 返回类型:返回右端无空格的字符串。
Note: trimRight()
is an alias for trimEnd()
注: trimRight()
是一个别名trimEnd()
翻译自: https://www.digitalocean.com/community/tutorials/js-trim-string-method