怎么提取特定字符串, 不用正则表达式提取

const value = "sum(value1 + value2) + dada - year(date)";
function fun(data){
}

console.log(fun(value))  // ['sum(value1 + value2)','year(date)'] 
阅读 1.9k
4 个回答

字符串可以用split函数来分成多个数组元素。
如果字符串有规律,就可以进行提取。比如这里:

function fun(data){
    return data.split(" + dada - ")
}

如果运算符(+-*/)两边都有空格,那就用空格做分割,然后遍历数组,将成对的扩号组合起来

const str = "sum(value1 + value2) + dada - year(date)";

function fun(data){
  const arr = data.split(' ');
  const res = [];
  let currentFun = [];
  arr.forEach(s => {
    if (s.indexOf(')') > -1) {
      currentFun.push(s);
      res.push(currentFun.join(' '));
      currentFun = [];
    } else if (s.indexOf('(') > -1 || currentFun.length) {
      currentFun.push(s);
    }
  })
  return res;
}
fun(str)
const str = 'ssse'
for(let i = 0;i< str.length; i ++ ){
    console.log(str.charAt(i))
}

不过还是用正则最好

const str = '(data-hhh-ss)'
const re = /\(\s*(\S+)\s*\)/
const execResult = re.exec(str)
console.log(execResult)

简单方便

function fun(data) {
    var ret = [];
    var index = 0;
    var name = "";
    var stack = [];
    return (function parse() {
        var input = "";
        do {
            var char = data[index++];
            if (char === "") continue;
            if (stack.length) input += char;
            switch (char) {
                case " ":
                    if (name) name = "";
                    break;
                case "(":
                    if (!name) break;
                    stack.push(name);
                    name = "";
                    input += parse();
                    break;
                case ")":
                    if (!stack.length) break;
                    ret.push(stack.pop() + "(" + input);
                    if (stack.length) {
                        return input;
                    } else if (input) {
                        input = "";
                        break;
                    }
                default:
                    name += char;
                    break;
            }
        } while (index < data.length);
        return ret;
    })();
}
console.log(fun("sum(value1 + value2)"));
console.log(fun("sum(value1 + value2) + dada - year(date)"));
console.log(fun("sum(value1 + subtract(value2 - value3)) + dada - year(date)"));
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题