JCA
JCA

Reputation: 287

Angular/Typescript regex function failing

I'm trying out this function so that I can map ID's to values, but the regex part of the function is not working.

Here is the part of the function I am having issues with:

xml2js.parseString(this.xml, (err, result) => {
      result = result['cm:property-placeholder']['cm:default-properties'][0]['cm:property']
      this.regex = `/${this.uiListElement[0].$.id}.${this.uiListElement[0].UIElement[0].$.id}/`;
      console.log(this.regex);
      let m;
      for (let i = 0; i < result.length; i++) {
        console.log(result[i].$.name)
        if ((m = this.regex.exec(result[i].$.name)) !== null) {
          console.log(m);

          m.forEach((match, groupIndex) => {
            console.log(`Found match, group ${groupIndex}: ${match}`);
          });
        }
      }

When console.log'd:

this.regex is /hl7_file_type_[0-9].msgtype/

result[0].$.name is hl7_site_code but as you can see the first index which isn't a match is what breaks it.

I'm hoping in the if statement to match and the values.

Upvotes: 0

Views: 312

Answers (1)

superhawk610
superhawk610

Reputation: 2663

You can't call .exec on a string. If you want to dynamically create a regular expression, you need to use the RegExp class:

this.regex = new RegExp('my_regular_expression');

Note that the leading and trailing / must be omitted.

Upvotes: 1

Related Questions