When the regular expression matches the first (on "AB" ), this part of the string is consumed by the engine, so it doesn't match again, although your regular expression has a global flag ( 'g' ).
You can achieve the expected result by using positive lookahead ( (?=PATTERN) ) instead, which will not consume a match:
value = "Hello IBM" value = value.replace(/([AZ])\s(?=[AZ])/g, '$1') console.log(value)
To do this, do not remove the space if the next letter in uppercase is the first in the word, you can enlarge the lookahead pattern with the \b border of the word to make this restriction:
value = "Hello IBM Dude" value = value.replace(/([AZ])\s(?=[AZ]\b)/g, '$1') console.log(value)
Note As @CasimirHyppolite noted, the next letter must be optional, or the second regular expression will not work if the last character of the line is uppercase. Thus, the pattern ([^A-Za-z]|$) , which can be considered "not the letter or the end of the line."
Edit : simplify lookahead from (?=[AZ]([^A-Za-z]|$)) to (?=[AZ]\b) as suggested by @hwnd
source share