开发者

Get a part from a string

开发者 https://www.devze.com 2023-03-28 11:56 出处:网络
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

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"
0

精彩评论

暂无评论...
验证码 换一张
取 消