JSFiddle - React, Tailwind, and code Playground
by jfriend00
HTML
<div id="result"></div>
JavaScript
var testObj = [
{"regexStr": "/^foo/", "regStr": "foo"},
["regStr", "/^foo/gi"],
{"a": [{"b": "/^foo/", "c": "test"}, ["/^foo/", "test"]]}
];
function isArray(obj) {
return toString.call(obj) === "[object Array]";
}
function isObject(obj) {
return Object.prototype.toString.call(obj) === '[object Object]'
}
var regexTest = /^\/(.*)\/([gimy]*)$/;
function convertRegex(item) {
if (isArray(item)) {
// iterate over array items
for (var i = 0; i < item.length; i++) {
item[i] = convertRegex(item[i]);
}
} else if (isObject(item)) {
for (var prop in item) {
if (item.hasOwnProperty(prop)) {
item[prop] = convertRegex(item[prop]);
}
}
} else if (typeof item === "string") {
var match = item.match(regexTest);
if (match) {
item = new RegExp(match[1], match[2]);
}
}
return item;
}
var result = convertRegex(testObj);