首页 > 解决方案 > 在javascript中删除字符串中的多余空格

问题描述

我有一个文本,在删除特殊字符后 (!@#$%^&*()-=+`";:'><.?/) 并只显示字母和数字(以及像 23.4 这样的浮点数)它返回一些额外空间

    const input : 'this is a signal , entry : 24.30 and side is short';

    const text = input.replace(/\.(?!\d)|[^\w.]/g, " ").toUpperCase();

    console.log(text.split(" "))

输出 :

[
  'THIS',   'IS',    'A',
  'SIGNAL', '',      '',
  '',       'ENTRY', '',
  '',       '24.30', 'AND',
  'SIDE',   'IS',    'SHORT'
]

但我想成为这样:

[
  'THIS',   'IS',    'A',
  'SIGNAL', 'ENTRY', '24.30',  
  'AND',    'SIDE',   'IS',     
  'SHORT'
]

当我替换空格并用空字符串输入时,返回:

[ 'THISISASIGNALENTRY24.30ANDSIDEISSHORT' ]

我的代码有什么问题?

标签: javascriptstringwhitespace

解决方案


不要替换,而是考虑匹配您想要生成单词数组的所有类型的字符。看起来你想要这样的东西:

const input = 'this is a signal , entry : 24.30 and side is short';
const matches = input.toUpperCase().match(/[\w.]+/g);
console.log(matches);


推荐阅读