最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript regex replace - but only part of matched string? - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question edited Feb 19, 2010 at 12:15 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Feb 19, 2010 at 9:06 Josef RichterJosef Richter 5071 gold badge9 silver badges16 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

$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.

发布评论

评论列表(0)

  1. 暂无评论