删除逗号和任何字母之间的空格

Remove white spaces from string between comma and any letter

本文关键字:之间 空格 任何字 删除      更新时间:2023-09-26

我使用RegExp和"string"。很少匹配,所以我不太确定如何在一些复杂的事情上使用它们。这是我想做但不知道怎么做的事情。这里我有一个javascript字符串

var str= " I would like to know how to use RegExp    ,    string.match    and  string.replace"

我想删除逗号和任何字母之间的所有空白。在那之后,这个字符串看起来是这样的

    str= " I would like to know how to use RegExp,string.match    and  string.replace"

我只知道如何从字符串中删除所有空白使用这个->

str = str.replace(/'s/g, "")

应该可以了:

str = str.replace(/'s*,'s*/g, ",");

var str = " I would like to know how to use RegExp    ,    string.match    and  string.replace";
console.log(
  str
);
console.log(
  str
  //Replace double space with single
  .replace(/  +/ig, ' ')
);
console.log(
  str
  //Replace double space with single
  .replace(/  +/ig, ' ')
  //Replace any amount of whitespace before or after a `,` to nothing
  .replace(/'s*,'s*/ig, ',')
);

使用RegEx:

's*,'s*
演示

您可以尝试使用正则表达式,并在https://regex101.com

上获得有关该语言特性的体面文档。

这是这个。lau_的解决方案:https://regex101.com/r/aT7pS5/1

我甚至会建议一个更好的包括引号:

const text: string = 'Example "number-1" , something “ABC” , and something more.';
const regex: RegExp = /'s(?=[,"”])/g;
const resultat: string = text.replace(regex, '');
Example "number-1", something “ABC”, and something more.