views:

130

answers:

2
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>
+2  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, '');
Greg
actually i need to remove the last square brackets on each iteration
gwegwegw
+1  A: 

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.

Jonas