Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (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?

like image 592
Josef Richter Avatar asked Feb 19 '10 09:02

Josef Richter


People also ask

What does \\ mean in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What is $1 in replace JavaScript?

In your specific example, the $1 will be the group (^| ) which is "position of the start of string (zero-width), or a single space character". So by replacing the whole expression with that, you're basically removing the variable theClass and potentially a space after it.

What is $1 in regex replace?

$1 is the first group from your regular expression, $2 is the second. Groups are defined by brackets, so your first group ($1) is whatever is matched by (\d+). You'll need to do some reading up on regular expressions to understand what that matches.

How do you replace a section of a string in regex?

To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring. The string 3foobar4 matches the regex /\d. *\d/ , so it is replaced.


2 Answers

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

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

like image 171
user187291 Avatar answered Sep 30 '22 13:09

user187291


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.

like image 26
Turismo Avatar answered Sep 30 '22 13:09

Turismo