将标准算术字符串转换为由管道分隔的BODMAS字符串

时间:2020-02-25 20:42:06

标签: javascript html

我需要找到一种方法,将以字符串形式编写的标准算术公式转换为另一种以计算格式表示的字符串,将BODMAS实施为一堆值和操作,其中每个值和操作都由从左到右读取的管道来界定。

我不想要公式的结果,我正在尝试编写一个JavaScript函数,该函数可以添加到HTML页面中,用户可以在其中输入公式(示例10 * 6 / 2),并验证公式,然后转换为另一个公式(结果为10|6|multiply|2|divide)。它从一种字符串格式转换为另一种字符串格式。

我已经有了另一个函数,该函数知道如何处理以这种方式编写的公式,我只需要避免强迫用户以不熟悉的方式编写公式,因此我需要在界面上完成此翻译。

到目前为止,我一直在尝试使用split函数,但是我还无法弄清楚如何扩展它来创建bodman_value。我的JavaScript技能很基本。这是我去过的地方,任何建议如何使用它的建议都会受到赞赏。

const str = '10 * 6 / 2';

const value_1 = str.split(' ');
console.log(value_1[0]);
// expected output: "10"

const operator_1 = str.split(' ');
console.log(operator_1[1]);
// expected output: "*"

const value_2 = str.split(' ');
console.log(value_2[2]);
// expected output: "6"

const operator_2 = str.split(' ');
console.log(operator_2[3]);
// expected output: "/"

const value_3 = str.split(' ');
console.log(value_3[4]);
// expected output: "2"

// expected output: Array ["10","*","6","/", "2"]

// assuming operator always at arroay 'odd' position (strCopy array is 0-4)

// count operators by number of odd positions in array

// then loop to get operator name of each array f_operator 

IF strCopy.[i] = "*" THEN f_operator.[i] = "multiply"
IF strCopy.[i] = "+" THEN f_operator.[i] = "add"
IF strCopy.[i] = "-" THEN f_operator.[i] = "subtract"
IF strCopy.[i] = "/" THEN f_operator.[i] = "divide"

var bodman_value

//    FOR loop f from 0 to array count

 bodman_value = strCopy.[f]] + "|" + strCopy.[f+2] + "|" + operator.[f]
 IF array count > 3
 bodman_value = bodman_value + "|"
 else

谢谢。

1 个答案:

答案 0 :(得分:2)

如果您有图案

value [operator, value]+

您只需将重复的运算符值部分切换为

value [value, operator]+

var operators = {
        '*': 'multiply',
        '/': 'divide'
    },
    string = '10 * 6 / 2',
    tokens = string.split(/\s+/),
    i = 0,
    result = [tokens[i++]];

while (i < tokens.length) {
    result.push(tokens[i + 1], operators[tokens[i]]);
    i += 2;
}

console.log(result.join('|'));

使用正则表达式和替换函数的更短方法。

var operators = {
        '*': 'multiply',
        '/': 'divide',
        '+': 'plus'
    },
    string = '24 + 6 / 10 * 100',
    result = string.replace(/\s+([^\s]+)\s+([^\s]+)/g, (_, o, v) => `|${v}|${operators[o]}`);

console.log(result);