javascript拆分 [英] javascript split

查看:83
本文介绍了javascript拆分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用JavaScript的拆分将逗号分隔的项列表放在数组中:

I can use JavaScript's split to put a comma-separated list of items in an array:

var mystring = "a,b,c,d,e";
var myarray = mystring.split(",");

我想到的是有点复杂。我有这个以逗号分隔的字符串:

What I have in mind is a little more complicated. I have this comma separated string:

"mystring_109_all,mystring_110_mine,mystring_125_all"

如何将此字符串拆分为数组

how do i split this string in to an array

推荐答案

您可以为 split()正则表达式 em>,所以要分割逗号或下划线,请使用以下内容:

You can provide a regular expression for split(), so to split on a comma or an underscore, use the following:

var mystring = "mystring_109_all,mystring_110_mine,mystring_125_all";
var myarray  = mystring.split(/[,_]/);

如果你想要更有活力的东西,你可能想尝试像搜索并不替换,一种使用 replace()<的方法/ em>解析复杂字符串的函数。例如,

If you're after something more dynamic, you might want to try something like "Search and don't replace", a method of using the replace() function to parse a complex string. For example,

mystring.replace(/(?:^|,)([^_]+)_([^_]+)_([^_]+)(?:,|$)/g,
  function ($0, first, second, third) {
    // In this closure, `first` would be "mystring",
    // `second` would be the following number,
    // `third` would be "all" or "mine"
});

这篇关于javascript拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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