在JavaScript中使用Trim String方法

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值