首页 > 解决方案 > 如何在javascript中拆分字符串包含分隔符?

问题描述

我有像“ 1 + 2 - 3 + 10”这样的字符串。我想将其拆分为"1", "+2", "-3", "+10".

这是我的代码。

var expression = "1 + 2 - 3 + 10";
expression = expression.replace(/\s+/g, '');
let fields = expression.split(/([+-]\d+)/g);
console.log(fields);

但结果是

["1", "+2", "", "-3", "", "+10", ""]

我怎样才能做出结果["1", "+2", "-3", "+10"]

标签: javascriptregex

解决方案


您的正则表达式需要一组

/([+-]\d+)/
 ^       ^  group 

它包含在结果集中。

结果,您为每个后续迭代获得两个部分,即来自组的先前部分和组本身。

"1"    first find
"+2"   group as separator for splitting, included to result set
 ""    second find, empty because of the found next separator
"-3"   second separator/group
""     third part without separator
"+10"  third separator
""     rest part between separator and end of string

您可以使用运算符的积极前瞻来拆分。

const
    string = '1 + 2 - 3 + 10',
    result = string.replace(/\s+/g, '').split(/(?=[+-])/);

console.log(result);


推荐阅读