Reputation: 2189
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
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 matchMore
Upvotes: 2
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 rightconst regex = /(\d) +(?=G)/g;
console.log("XXX YYY AAA 16Gb 16 Gb 16 G 2 G ZZZ".replace(regex, "$1"));
Upvotes: 3
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