Why doesn't this JavaScript function remove square brackets one by one?
var asdf = "a[3] > b[5] > c[1]"
function removebracket(){
var newstring = asdf.replace(/\/[^\/]*$/, '')
alert(newstring);
}
<a href="#" onClick="javascript:removebracket();"> remove square brackets one by one </a>开发者_运维技巧
Your regular expression doesn't do anything like remove brackets - it looks like it's for removing parts from a path. This will remove square brackets:
var newstring = asdf.replace(/\[|\]/g, '');
A little explaining of the regex you have:
/\/[^\/]*$/
The string between the first and the last /
is the regex
\/[^\/]*$
Here the \/
is matching a /
since the \
is used for escaping special characters, like /
.
[^\/]
Everything between square brackets []
will match exactly one character. ^
inside the brackets means it'll match everything except the next char. Hence [^\/]
will match everything except a /
.
The *
matches zero or more of the previous character.
Lastly the $
matches end of the string or a newline.
Use it with /foo/bar
and you'll end up with /foo
.
精彩评论