Home > Mobile >  RegEx works in online testers, but returns `null` match both in my app and the online sandboxes
RegEx works in online testers, but returns `null` match both in my app and the online sandboxes

Time:12-05

I am working on a regular expression that would extract all headings from a parsed MDX string. It looks fine in two online testers (enter image description here

But does not work outside the online testers :(:

let testString = `dx(\"p\",null,\"In this tutorial, we will create an \",mdx(\"em\",{parentName:\"p\"},\"input for code blocks\"),\" in \",mdx(\"strong\",{parentName:\"p\"},\"Sanity.io\"),\". Subsequently, we will create a \",mdx(\"em\",{parentName:\"p\"},\"component for displaying our code blocks\"),\" in \",mdx(\"strong\",{parentName:\"p\"},\"Next.js\"),\" app.\"),mdx(\"h2\",null,\"Prerequisities\"),mdx(\"ul\",null,mdx(\"li\",{parentName:\"ul\"},\"We already know how to install and use Sanity Studio (it is \",mdx(\"a\",e({parentName:\"li\"},{href:\"https://www.sanity.io/docs/getting-started-with-sanity-cli\"}),\"pretty straighforward\"),\").\"),mdx(\"li\",{parentName:\"ul\"},\"We already know how to install Next.js and connect it to Sanity api. In the case of uncertainity, there is a \",mdx(\"a\",e({parentName:\"li\"},{href:\"https://www.sanity.io/blog/build-your-own-blog-with-sanity-and-next-js\"}),\"great tutorial on the company blog\"),\".\")),mdx(\"h2\",null,\"How to add the code input to Sanity\"),mdx(\"p\",null,\"Sanity.io does not come with a dedicated input for code blocks out of the box, but there is a nice \",mdx(\"a\",e({parentName:\"p\"},{href:\"https://www.sanity.io/plugins/code-input\"}),\"official plugin\"),`

console.log(testString.match(/(?<=mdx\()\\"h\d(?:(?!\),).)*/gi))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Why is that? How should I correct my expression to make it work?

Any advice would be much appreciated.

CodePudding user response:

Your test string has no backslashes (those that are present in the template literal are escapes, not literal backslashes), yet your regex looks for them. The online regex-test sites will treat them as literal backslashes.

Simple solution: use String.raw:

let testString = String.raw`....your string with backslashes...`;
  • Related