Search code examples
javascriptjsonregexstringobject

How to pass regex expression in JSON to API?


How can I pass RegEx in JSON to API without stringify it? Below is two code that refer what i want and what actually passing to API. I don't need to convert to stringify. Thanks in advance

//JSON I want to pass
{
    "data": {
        "type": "wood-species",
        "attributes": {
            "description": "test126",
            "abbreviation": /([A - Z])\ w +/  <-REGEX that i want to pass
        }
    }
    }
//JSON that actually pass
{
    "data": {
        "type": "wood-species",
        "attributes": {
            "description": "test126",
            "abbreviation": {}   <-REGEX that actually pass(making regex an empty object)
        }
    }
}

Solution

  • You can't store a regex in a JSON string. You'd need to store it as an actual string and recreate it on the receiving end with the RegExp constructor (also slice off the leading and trailing slashes /).

    const obj = {
      "abbreviation": "/([A - Z])\w+/"
    };
    
    const stringified = JSON.stringify(obj);
    const regex = new RegExp(JSON.parse(stringified).abbreviation.slice(1, -1));
    console.log(regex);