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
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/