JavaScript regex replace - but only part of the matched string?

I have the following replacement function

myString.replace(/\s\w(?=\s)/,"$1\xA0"); 

The goal is to take single-letter words (e.g. prepositions) and add inextricable space after them instead of the standard space.

However, the above variable $ 1 does not work for me. It inserts the text "$ 1" instead of part of the original matched string + nbsp.

What is the reason for the observed behavior? Is there any other way to achieve it?

+7
javascript regex replace typography
source share
2 answers

$ 1 does not work because you do not have any capturing subgroups.

The regular expression should be something like /\b(\w+)\s+/ .

+9
source share

It seems you want to do something like this:

 myString.replace(/\s(\w)\s/,"$1\xA0"); 

but in this way you lose the spaces in front of your one-letter word. Therefore, you probably want to include the first \s in the capture group as well.

+5
source share

All Articles