简体   繁体   中英

Special characters for removing multi spaces in Javascript

I am removing multi spaces from a text. I cant understand what does the comma do after the "2". On https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions it says that just the "{2}" should locate all the doubles.

return newsong.replace(/\s{2}/g, ' ')

return newsong.replace(/\s{2,}/g, ' ')

Very confused....

The comma matches 2 or more spaces, allowing you to remove spaces from strings like:

part1     part2

as well. If you use the first regex on this one (no comma), it'll see this:

part1<SPACE><SPACE><SPACE><SPACE><SPACE>part2

The first two spaces are removed, then the next two, leaving you with

part1<SPACE>part2

This last space isn't matched by \\s{2} and will remain. If you use the comma, it'll just remove them all in one go because that matches 2 or more spaces.

Also, if you put another number after the comma, you can set a maximum number of spaces to match.

The range meta sequence consist of two parts, minimum matches and maximum matches.

{n, m}

Where n is minimum and m is maximum.

When only one is specified it's considered as both minimum and maximum, eg: x{2} will match two x'es

When manimum is omitted it will match 0 .. maximum times, eg: x{,2} will match zero, one or two x'es

When maximum is omitted it will match minimum or more times, eg: x{2,} will match two or more x'es

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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