删除字符串中单词之间的空格 javascript js React

hel*_*297 -1 javascript regex removing-whitespace reactjs

我正在使用 React(钩子),并且在一个组件中我有邮政编码,字符串中有一个空格:例如“B72 1JL”。

我需要删除邮政编码中间的空格,所以它是“B721JL”,也可能是邮政编码之前或之后的任何空格。

我已经用谷歌搜索了很长时间,找不到任何有用的东西。我知道我可能需要正则表达式……但很困惑!
帮助表示赞赏。

Cla*_*tto 9

使用String.prototype.replace()将空间更改为空白空间。

const str = "B72 1JL";

// Replacing " " (space) to "" empty space
const res = str.replace(/ /g, '')
console.log(res); // BJ721JL
Run Code Online (Sandbox Code Playgroud)

  • 这只替换了一个空格。要替换所有空格,您可以使用 `str.replace(/ /g, '')` (2认同)