regex to find match if a colon character exists between double curly brackets {{key:value}}

  Kiến thức lập trình

I am trying to refactor the method below to use regex instead of indexOf:

hasMatch(value: any): boolean {
    if (isDefined(value)) {
      const valueStr = JSON.stringify(value);
      return valueStr.indexOf('{{') > -1 && valueStr.indexOf(':') > -1;
    } else {
      return false;
    }
  }

Currently it simply checks if there are double brackets “{{” and a colon in the string. This means I matches colons outside of the replacement strings, which I don’t want.

I need to only return a match if a colon exists between two double brackets with key/value pairs like: {{key:value}}

Here is what I’ve cobbled together using some examples here (I’m obviously a complete regex newb):

const matches = valueStr.match(/{{({^}{}*)}}/g).map(x => `[${x.replace(/[^:]/g, '')}]`)

But I’m currently stuck on this error:

main.js:66071 ERROR TypeError: Cannot read properties of null (reading 'map')

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website Kho Theme wordpress Kho Theme WP Theme WP

LEAVE A COMMENT