JavaScript regex replace - but only part of matched string?

Josef Richter picture Josef Richter · Feb 19, 2010 · Viewed 10.1k times · Source

I have the following replace function

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

The aim is to take single-letter words (e.g. prepositions) and add a non-breaking space after them, instead of standard space.

However the above $1 variable doesn't work for me. It inserts text "$1 " instead of a part of original matched string + nbsp.

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

Answer

user187291 picture user187291 · Feb 19, 2010

$1 doesn't work because you don't have any capturing subgroups.

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