如何在不对其进行字符串化的情况下将 JSON 中的 RegEx 传递给 API?下面是两个代码,它们引用了我想要的和实际传递给 API 的内容。我不需要转换为字符串化。提前致谢
//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)
}
}
}
最佳答案
您不能将正则表达式存储在 JSON 字符串中。您需要将其存储为实际字符串并在接收端使用 RegExp
构造函数重新创建它(同时切掉前导和尾随斜杠 /
)。
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);
关于javascript - 如何将 JSON 中的正则表达式传递给 API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56471002/