最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove white spaces from string between comma and any letter - Stack Overflow

programmeradmin3浏览0评论

I use RegExp and "string".match very rarely so I'm not so sure how to use them for some little bit complex things.Here's what I would like to do and don't know how to do it. Here I have a string in javascript.

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

I would like to delete all white spaces BETWEEN comma and any letter.So after that this string will look like this.

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

I only know how to delete all white spaces from string using this-->

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

I use RegExp and "string".match very rarely so I'm not so sure how to use them for some little bit complex things.Here's what I would like to do and don't know how to do it. Here I have a string in javascript.

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

I would like to delete all white spaces BETWEEN comma and any letter.So after that this string will look like this.

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

I only know how to delete all white spaces from string using this-->

str = str.replace(/\s/g, "")
Share Improve this question edited Sep 26, 2016 at 13:25 j08691 208k32 gold badges267 silver badges280 bronze badges asked Sep 26, 2016 at 13:23 MatijaMatija 5334 gold badges9 silver badges21 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 19

That should work:

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, ',')
);

Simply use RegEx:

\s*,\s*

DEMO

You can play around with regex expressions and get a decent documentation of the language features on https://regex101.com

Here is this.lau_'s solution of your problem: https://regex101.com/r/aT7pS5/1

I would even suggest a better one that includes quotes:

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.
发布评论

评论列表(0)

  1. 暂无评论