dthree
dthree

Reputation: 20730

Regex in JS - Add match to replace

I can't find the solution to this anywhere, but I think it's because I don't have the terminology right.

I have this:

var text = "Foo:Bar"; // I want -> "Foo: Bar"
text = text.replace(new RegExp("Foo:[a-z]", "ig"), "Foo: ");

I have lots of foos, and I want to add a space after the colons. I only want to do it if I can tell the colon has a letter right after it. However, when I do the above, I get:

// -> "Foo: ar"

How do I take that [a-z] match, and throw it into the end of the replace?

Upvotes: 1

Views: 46

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174696

What you need is a positive lookahead assertion. [a-z] in your regex consumes an alphabet but a lookaround won't consume a character. (?=[a-z]) this positive lookahead asserts that the match (Foo:) must be followed by an alphabet. So this regex will match all the Foo: strings only when it is followed by an alphabet. Replacing the matched Foo: with Foo:<space> will give you the desired output.

text = text.replace(new RegExp("Foo:(?=[a-z])", "ig"), "Foo: ");

OR

text = text.replace(/Foo:(?=[a-z])/ig, "Foo: ");

Upvotes: 2

dfsq
dfsq

Reputation: 193261

You can use simple capturing group and reference it as $1 in replace string:

var text = "Foo:Bar"; // I want -> "Foo: Bar"
text = text.replace(new RegExp("Foo:([a-z])", "ig"), "Foo: $1");

alert(text);

Also I would use regexp literal expression instead of contructor:

text = text.replace(/Foo:([a-z])/ig, "Foo: $1");

Upvotes: 1

Related Questions