javascript - 如何在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"]
?
解决方案
您的正则表达式需要一组
/([+-]\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);
推荐阅读
- symfony - Bazinga 翻译包返回键
- flutter - 安装 Zefyr(Flutter) 时出错找不到方法:'SystemNavigator.routeInformationUpdated'
- sql - 如何使用 FOR JSON AUTO 从 SQL SERVER 中的变量创建 JSON
- javascript - 如何设置 WebSocket.send() 的块大小?
- html - 隐藏选择框
- python - OSError:无法加载共享对象文件:llvmlite.dll(SHAP 相关。可能缺少什么?)
- python - 如何将具有重复系列值的列添加到数据框中?
- graphql - Strapi Graphql 深度排序
- javascript - 防止刷新提交并在提交后清除输入
- mysql - 尝试在MYSQL中使用Insert On Duplicate Key更新命令,但是一张表没有PK