JavaScript拆分任意数量的字符

问题描述 投票:-2回答:2

是否可以在JavaScript中拆分任意数量的字符,可能使用正则表达式?

例:

“这些是____下划线”将返回["These are ", " underscores"]

这是我到目前为止所拥有的:

"These are ____ underscores".split("_").filter(x => x);

但是,我不确定是否有更有效/更好的方法来做到这一点。

谢谢。

javascript
2个回答
5
投票

let x = 'These are ____ underscores';
let y = x.split(/_+/);
console.log(y);

1
投票

您可以按字符拆分,然后过滤非空数组:

var str = "These are ____ underscores"
str.split("_").filter(x => x.length)
© www.soinside.com 2019 - 2024. All rights reserved.