简体   繁体   English

删除 javascript 中字符串中的多余空格

[英]remove extra spaces in string in javascript

I have a text and after deleting special characters (;@#$%^&*()-=+`":.'><?./) and show just letters and numbers (and float numbers like 23.4 ) it returns some extra space我有一个文本,在删除特殊字符 (;@#$%^&*()-=+`":.'><?./) 并仅显示字母和数字(以及浮点数,如 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(" "))

the output: output:

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

but I want to be this:但我想成为这样的人:

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

And when I replace spaces and enters with empty string, returns this:当我替换空格并输入空字符串时,返回:

[ 'THISISASIGNALENTRY24.30ANDSIDEISSHORT' ]

what is the problem of my code?我的代码有什么问题?

Instead of replacing, consider matching all the sorts of characters you want to produce the array of words.不要替换,而是考虑匹配您想要生成单词数组的所有类型的字符。 It looks like you want something like:看起来你想要这样的东西:

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

The second parameter in the replace method needs to be an empty string and not a space as you have it in your code. replace方法中的第二个参数需要是一个空字符串,而不是代码中的空格。

Just do:做就是了:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM