查找字符串中的js对象的方法

36 阅读1分钟

匹配字符串中的js对象的正则表达式

记录如果匹配js对象的正则表达式

      let result = "";
      const stack = [];
      const objStr = [];
      let start = -1;
      for (let i = 0; i < str.length; i++) {
        if (str[i] == '{') {
          if (stack.length == 0) {
            start = i;
          }
          stack.push(str[i]);
        } else if (str[i] == '}') {
          if (stack.length > 0) {
            stack.pop();
            if (stack.length === 0 && startIndex !== -1) {
              objStr.push(str.slice(start, i + 1));
              start = -1;
            }
          }
        }
      }

采用匹配大括号进栈出栈的方式进行匹配。