在 Javascript 中使用内部和外部分隔符分割字符串

发布于 2024-10-19 06:05:13 字数 256 浏览 2 评论 0原文

在我的 Javascript 代码中,我有一个像这样的字符串:

"1943[15]43[67]12[32]"

我想返回一个像这样的数组:

["1","9","4","3","15","4","3","67","1", 2","32"]

也就是说,我希望它分隔每个字符,除了括号内的数字,我想将其保留为一个元素。

有没有一种优雅的方法来做到这一点?

In my Javascript code, I have a string that is something like this:

"1943[15]43[67]12[32]"

I want to return an array like this:

["1","9","4","3","15","4","3","67","1", 2","32"]

That is, I want it to separate every character, except the numbers inside the brackets, which I want to preserve as one element.

Is there an elegant way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

清醇 2024-10-26 06:05:13
var str = '1943[15]43[67]12[32]',
    matches = str.match(/\d|\[\d+\]/g);

for (var i = 0, matchesLength = matches.length; i < matchesLength; i++) {
    matches[i] = matches[i].replace(/\D/g, '');
};

console.log(matches);
// ["1", "9", "4", "3", "15", "4", "3", "67", "1", "2", "32"]

jsFiddle

var str = '1943[15]43[67]12[32]',
    matches = str.match(/\d|\[\d+\]/g);

for (var i = 0, matchesLength = matches.length; i < matchesLength; i++) {
    matches[i] = matches[i].replace(/\D/g, '');
};

console.log(matches);
// ["1", "9", "4", "3", "15", "4", "3", "67", "1", "2", "32"]

jsFiddle.

胡大本事 2024-10-26 06:05:13
var str = "1943[15]43[67]12[32]", 
    re = new RegExp(/(\d)|\[(\d+)\]/g), 
    out = [],
    m;

while (m = re.exec(str)) { 
  out.push(m[2] || m[0]); 
}

console.log(out); // ["1", "9", "4", "3", "15", "4", "3", "67", "1", "2", "32"]
var str = "1943[15]43[67]12[32]", 
    re = new RegExp(/(\d)|\[(\d+)\]/g), 
    out = [],
    m;

while (m = re.exec(str)) { 
  out.push(m[2] || m[0]); 
}

console.log(out); // ["1", "9", "4", "3", "15", "4", "3", "67", "1", "2", "32"]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文