由Regex结果子字符串拆分的JavaScript字符串包括空切片 [英] JavaScript string split by Regex results sub-strings include empty slices

查看:97
本文介绍了由Regex结果子字符串拆分的JavaScript字符串包括空切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字符串拆分JavaScript代码:

I've the following string splitting JavaScript code:

var formula = "(field1 + field2) * (field5 % field2) / field3";
console.log(formula.split(/[+(-)% *\/]/));

结果超出预期:

["", "field1", "", "", "field2", "", "", "", "", "field5", "", "", "field2", "", "", "", "field3"]

所需要的是什么结果将是:

What the desired result would be:

["field1", "field2", "field5", "field2", "field3"]

我正在使用Google Chrome 11正式版作为测试浏览器,请告知我正在做什么错误。

I'm using Google Chrome 11 official release as the testing browser, please kindly advise what I'm doing wrong.

谢谢!

William

推荐答案

而不是拆分 / [+( - )%* \ /] / 拆分多个: / [+( - )%* \ /] + / 。你仍然可能在开始和结束时获得空匹配。要解决这个问题,您可以使用类似的正则表达式替换:

Instead of splitting on /[+(-)% *\/]/ split on more than one: /[+(-)% *\/]+/. You still might get empty matches at the start and end. To solve that problem you can use a similar regex with replace:

formula.replace(/^[+(-)% *\/]+|[+(-)% *\/]+$/g, "").split(/[+(-)% *\/]+/)

所以

var formula = "(field1 + field2) * (field5 % field2) / field3";
console.log(formula.replace(/^[+(-)% *\/]+|[+(-)% *\/]+$/g, "").split(/[+(-)% *\/]+/));

收益率

field1,field2,field5,field2,field3

这篇关于由Regex结果子字符串拆分的JavaScript字符串包括空切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆