1

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?

2
  • Whats wrong with the regex you have? Just add a capture group. text = text.replace( /Foo:([a-z])/ig, 'Foo: $1'); Commented Dec 13, 2014 at 18:09
  • @sin, I didn't know what a capture group was... Commented Dec 13, 2014 at 22:17

2 Answers 2

2

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: ");
Sign up to request clarification or add additional context in comments.

1 Comment

++ for nailing it, and for telling me what it's called. That worked! Thanks.
1

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");

1 Comment

This is what I was originally thinking of. Thanks and I'll use that in the future!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.