I have a input field with this name:
myinput[something][etc]
How can I get the contents from the last []
part from it? i.e.开发者_JAVA技巧 etc
in this case?
If you know that the string ends with the ]
, you can use simple string operations:
var name = "myinput[something][etc]";
var index = name.lastIndexOf('[');
var last = name.substr(index + 1, name.length - index - 2);
You can use a regular expression to match whatever is in between the last pair of []
. Because [
and ]
have special meaning in regexp (they are used to delimit character classes), you have to escape them with \
. The entire match (aside from the [
and the ]
) is anchored at the end of the string using $
.
var s = 'myinput[something][etc]',
re = /\[([^\]]*)\]$/
text = re.exec(s)[1]; // "etc"
精彩评论