javascript - 在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' ]
我的代码有什么问题?
解决方案
不要替换,而是考虑匹配您想要生成单词数组的所有类型的字符。看起来你想要这样的东西:
const input = 'this is a signal , entry : 24.30 and side is short';
const matches = input.toUpperCase().match(/[\w.]+/g);
console.log(matches);
推荐阅读
- c++ - 理解 char* - C++
- sql - 查找 2 个表 sql 之间的差异以及如何获得更改的值?
- swiftui - SwiftUI - 动画过渡
- python - Flask 方法 PUT 没有返回一些东西
- docker - mariadb容器上的exec命令出现问题
- php - 如何连接用户选择的今天的日期和小时以将其插入为日期时间
- xml - 使用 XSLT 中单个 xml 字段的计数填充页脚行
- oracle - 在 makefile 中设置动态 ORACLE_HOME
- sql - 比较sql中列号不同的两张表
- python - ungoogled-chromium-windows 构建失败,出现“致命错误:'atlsecurity.h' 文件未找到”