在数字和字符之间插入空格

Zah*_*man 3 javascript string jquery

我有一个数学方程

var equation="(4+5.5)*3+4.5+4.2";
Run Code Online (Sandbox Code Playgroud)

当我做

equation.split('').join(' ');
Run Code Online (Sandbox Code Playgroud)

它得到输出,每个字符之间有空格。

( 4 + 5 . 5 ) * 3 + 4 . 5 + 4 . 2
Run Code Online (Sandbox Code Playgroud)

如何在数字和字母字符之间插入空格?

样本输出:

( 4  +  5.5 ) *  3  +  4.5  +  4.2
Run Code Online (Sandbox Code Playgroud)

有任何人可以帮助我如何弄清楚,谢谢。

Nin*_*olz 5

您可以填充操作员。

var string = "(4+5.5)*3+4.5+4.2",
    result = string.replace(/[+\-*/]/g, ' $& ');

console.log(result);
Run Code Online (Sandbox Code Playgroud)

带括号的空格。

var string = "(4+5.5)*3+4.5+-4.2",
    result = string
        .replace(/[+\-*/()]/g, ' $& ')
        .replace(/([+\-*/]\s+[+\-])\s+/, '$1')
        .replace(/\s+/g, ' ').trim();

console.log(result);
Run Code Online (Sandbox Code Playgroud)