Azevedo
Azevedo

Reputation: 2189

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

Upvotes: 1

Views: 119

Answers (3)

Shakiba Moshiri
Shakiba Moshiri

Reputation: 23774

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

Upvotes: 2

The fourth bird
The fourth bird

Reputation: 163217

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"));

Upvotes: 3

Isaac Vega
Isaac Vega

Reputation: 330

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

Upvotes: 1

Related Questions