up vote 0 down vote favorite
share [fb]

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?

link|improve this question

33% accept rate
feedback

2 Answers

up vote 2 down vote accepted

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

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

link|improve this answer
yes, that "capturing group" was the piece I was missing. Thank you very much! – Josef Richter Feb 19 '10 at 9:52
feedback

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.

link|improve this answer
hey, this works like charm! awesome, thank you so much. I didn't know about "capturing group" but was suspicious there's something like that. – Josef Richter Feb 19 '10 at 9:51
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.