我有一个包含一些字段的数组
像这样ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_17
ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_18
ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_19
我想创建一个新数组或操作此数组以仅包含
sid = {25,26,27}
这
_SID_25
_SID_26
_SID_27
其中sid将是我的数组,其中包含从上面的数组中提取的sid
使用模式_SID_
我必须在jquery或javascript中执行此操作
答案 0 :(得分:7)
使用jquery map + regexp
var arr= ['tl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_17',
'ctl00_ctl00_cphBody_bodycph_content_rdo_SID_26_SortOrder_18',
'ctl00_ctl00_cphBody_bodycph_content_rdo_SID_27_SortOrder_19']
var out = $(arr).map(function(){
return this.match(/SID_(.*?)_/)[1];
});
out应该是值的数组..
(假设数组中的所有值都与模式匹配)
答案 1 :(得分:4)
我会在这里使用正则表达式
var sid = []
var matches = "ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_17".match(/_SID_(\d+)/);
if(matches) sid.push(parseInt(matches[1]));
答案 2 :(得分:0)
这个解决方案完全依赖于整体字符串形式没有太大变化,即“下划线”的数量没有变化,这似乎是脆弱的,道具给了下面的评论者,但他的索引错了。我的原始解决方案首先拆分为“SID_”,因为这看起来更像是一个永远存在于字符串中的键。
假设:
s = "ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25344_SortOrder_17"
旧解决方案:
array.push(parseInt(s.split("SID_")[1].split("_")[0]))
新解决方案
array.push(parseInt(s.split("_")[7])