const value = "sum(value1 + value2) + dada - year(date)";
function fun(data){
}
console.log(fun(value)) // ['sum(value1 + value2)','year(date)']
const value = "sum(value1 + value2) + dada - year(date)";
function fun(data){
}
console.log(fun(value)) // ['sum(value1 + value2)','year(date)']
如果运算符(+-*/
)两边都有空格,那就用空格做分割,然后遍历数组,将成对的扩号组合起来
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)"));
10 回答11.3k 阅读
5 回答4.9k 阅读✓ 已解决
4 回答3.2k 阅读✓ 已解决
2 回答2.8k 阅读✓ 已解决
3 回答2.4k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
2 回答2.7k 阅读✓ 已解决
字符串可以用split函数来分成多个数组元素。
如果字符串有规律,就可以进行提取。比如这里: