如何在JavaScript中替换字符串内的空白

Replacing all the white space inside a string is a very common need.

替换字符串中的所有空白是非常普遍的需求。

For example I last used this inside an API endpoint that received an image. I used the original image name to store it, but if it contained a space it was breaking my functionality (or other special chars, but let’s focus on spaces)

例如,我上次在接收图像的API端点内使用了此方法。 我使用原始的图像名称来存储它,但是如果它包含一个空格,则会破坏我的功能(或其他特殊字符,但我们将重点放在空格上)

So I researched the best way to do what I wanted. Turns out, a regular expression was what I needed!

所以我研究了做我想要的最好的方法。 原来,我需要一个正则表达式

Here it is, in full

这是全部

const name = 'Hi my name is Flavio'
name.replace(/\s/g, '') //HimynameisFlavio

How to replace white space inside a string in JavaScript

The \s meta character in JavaScript regular expressions matches any whitespace character: spaces, tabs, newlines and Unicode spaces. And the g flag tells JavaScript to replace it multiple times. If you miss it, it will only replace the first occurrence of the white space.

JavaScript正则表达式中的\s元字符与任何空白字符匹配:空格,制表符,换行符和Unicode空格。 g标志告诉JavaScript多次替换它。 如果您错过它,它将仅替换第一次出现的空白。

Remember that the name value does not change. So you need to assign it to a new variable, if needed:

请记住, name值不会改变。 因此,如果需要,您需要将其分配给新变量:

const name = 'Hi my name is Flavio'
const nameCleaned = name.replace(/\s/g, '')

翻译自: https://flaviocopes.com/how-to-replace-whitespace-javascript/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值