views:

32

answers:

2
var somestring = "mary(3) apple(2) sky(1)";
$("#removelaststring").unbind("click").bind("click",function(e){

somestring = somestring.replace(/\(\d+\)*$/, "")
alert(somestring);

});

i should get

mary(3) apple(2) sky

then if i run it agan

mary(3) apple sky

if run again

mary apple sky

however this doesn't happen, no matter how many times i click i get

mary(3) apple(2) sky
+3  A: 

There's an anchor ($) in your regex which requires it to match at the end of the string only. No characters after "(2)" are permitted. I guess you want this

somestring = somestring.replace(/\(\d+\)([^(]*)$/, "$1")

allowing any characters but the '(' after the part that is removed. Assuming '(' is only going to appear as part of some "(2)".

Gleb
A: 

You are replacing '(n)' at the end of the string with '' (a blank string), so mary(3) apple(2) sky(1) becomes mary(3) apple(2) sky, but then the next time around, there is not a '(n)' any more, so no further replacement takes place.

Premasagar