简单的正则表达式可提取jQuery中方括号之间的内容 [英] Simple regex to extract contents between square brackets in jQuery

查看:440
本文介绍了简单的正则表达式可提取jQuery中方括号之间的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆元素的名称类似于"comp [1] .Field"或"comp [3] .AnotherField",其中索引(1或3)发生了变化.我正在尝试从名称中提取索引.

I have a bunch of elements with names similar to "comp[1].Field" or "comp[3].AnotherField" where the index (1 or 3) changes. I'm trying to extract the index from the name.

现在我正在使用:

var index = $(":input:last").attr("name").match(/\[(\d+)\]/)[1];

但是我不认为这是执行此操作的最佳方法.

but I don't feel like this is the best way to do this.

有什么建议吗?

谢谢

推荐答案

实际上,这是一个很好的方法,但是您应该添加一些检查,以确保match()实际上返回一个数组(表示字符串)被找到)并且不能为null,否则您将收到类型错误.

What you have is actually a pretty good way to do it, but you should add some checking that ensures that match() actually returns an array (meaning the string was found) and not null, otherwise you'll get a type error.

示例:

var index = $(":input:last").attr("name").match(/\[(\d+)\]/);
if (match) { index = match[1]; }
else { /* no match */ }

这篇关于简单的正则表达式可提取jQuery中方括号之间的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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