简体   繁体   中英

JavaScript regex replace - but only part of matched string?

I have the following replace function

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

The aim is to take single-letter words (eg 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?

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

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

Seems you want to do something like this:

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

but that way you will loose the whitespace before your single-letter word. So you probably want to also include the first \\s in the capturing group.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM