简体   繁体   中英

Javascript RegEx to replace white space between two specific expressions

I'm trying to remove space character from a string only when it is bewteen a number and the G letter.

Sample text: XXX YYY AAA 16Gb 16 Gb 16 G 2 G ZZZ

Target result: XXX YYY AAA 16Gb 16Gb 16G 2G ZZZ

What I have so far is:

'XXX YYY AAA 16Gb 16 Gb 16 G 2 G ZZZ'.replace(/\d+ gb?/ig, '?')

You could capture a digit and a space (or 1+ spaces) and assert the G at the right.

In the replacement use group 1 $1 and enable the /g flag to replace all occurrences and possibly /i for a case insensitive match.

(\d) +(?=G)
  • (\d) Capture a single digits
  • + Match 1+ spaces
  • (?=G) Positive lookahead, assert a G char to the right

Regex demo

 const regex = /(\d) +(?=G)/g; console.log("XXX YYY AAA 16Gb 16 Gb 16 G 2 G ZZZ".replace(regex, "$1"));

In new version of JS we have look-ahead and look-behind assertion which means you can do:

"XXX YYY AAA 16Gb 16 Gb 16 G 2 G ZZZ".replace( /(?<=\d) +(?=G)/g, "" )

and outputs:

"XXX YYY AAA 16Gb 16Gb 16G 2G ZZZ"

which says (?<=\d) +(?=G) :

  • (?<=\d) look-behind to find a single number but do include it in the match
  • + match one or more space(s)
  • (?=G) look-ahead to find G but do not include it in the match

More

You can achieve this easily by creating Regex groups. Notice the () surrounding both the digit and the "g" and then reusing them in the replace function by indexing them.

console.log("XXX YYY AAA 16Gb 16 Gb 16 G 2 G ZZZ".replace(/([\d])\s*(g)/ig, '$1$2'))

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