0

I have text like this:

....foo..bar....

foo and bar can be any text at all.

It could also be:

anypreamble....foo..bar....anypostamble

I'm trying to match just foo and just bar but I keep matching the entire thing.

Here's some code:

var s = "this....AAAAAAAAAA..BBBBCD....that";

console.log(s.replace(/\.{4}.+\.{2}(.+)\.{4}/g, 'X'));

I would expect the above to give me: thisAAAAAAAAAAXthat, instead it gives: thisXthat.

Can you help?

Here's a fiddle: https://jsfiddle.net/vfkzdg9y/1/

2
  • you're replacing the entire match with 'X', try using a capture group and backreference. Commented Jan 21, 2016 at 0:44
  • I thought the (.+) was the capture group... Commented Jan 21, 2016 at 0:53

2 Answers 2

1

If you want to get the two strings (foo and bar) separated with X, you can use:

var s = "this....AAAAAAAAAA..BBBBCD....that";

console.log(s.replace(/[^\.]*\.{4}([^\.]+)\.{2}([^\.]+)\.{4}.*/g, '$1X$2'));

Yields

AAAAAAAAAAXBBBBCD

You could also use:

console.log(s.replace(/[^\.]*\.{4}(.+)\.{2}(.+)\.{4}.*/g, '$1X$2'));

Which yields

AAAAAAAAAAXBBBB.CD

for your second example.

Sign up to request clarification or add additional context in comments.

1 Comment

This is good, but the text could literally be anything including fullstops, so I can't use the negate.
0

Try using RegExp /(\.{2}\w+)(?=\.{4}\w+$)|\./gto match two consecutive . characters followed by alphanumeric characters , if followed by four . characters followed by alphanumeric characters followed by end of string ; replace . with empty string, else return "X" for captured match

s.replace(/(\.{2}\w+)(?=\.{4}\w+$)|\./g, function(match) {
  return match === "." ? "" : "X"
})

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.