George Edwards George Edwards - 4 months ago 8
Node.js Question

regex .exec() loosing first digit of matched string

I am building a nodeJS JavaScript application and am trying to use regex to process some markdown files.

I have the following code:

var title = /```.(.*?\n)/.exec(codeBlock);
console.log('Code: ' + codeBlock);
console.log('Title: ' + title[1]);


and the output is:

Code: ```TypeScript
animationSet = new animationModule.Animation([{
target: view,
rotate: 360,
duration: 3000,
iterations: Number.POSITIVE_INFINITY,
curve: view.ios ? UIViewAnimationCurve.UIViewAnimationCurveLinear : new android.view.animation.LinearInterpolator
}]);
animationSet.play().catch((e) => {
console.log("Animation stopped!");
});
// Call animationSet.cancel() to stop it;
```
Title: ypeScript


Notice rather than the full "title" I am looking the first character. If I add a space, such that first line of the code block is
``` TypeScript
then I get an output of
Title: TypeScript
.

Where is my first character going and how can I get it back!

Answer

Helpful tool

hmmmm your capture group starts after first charater

/```.(.*?\n)/ 

it says :

  • ``` - this 3 charaters
  • . - one any charater <- here is your charater consumed but not captured
  • ( - start capture group
  • ...etc

so valid pattern will be :

```(.*?\n)