Test returns true, but replace does nothing

This is driving me freaking crazy. I have a RegExp, and a String. When I alert RegExp.test(String), I get “true.” Sweet. Then I run String.replace(RegExp, “”), in an attempt to get rid of whatever was matched. But that does not change the string at all.

Am I misunderstanding replace, or what?

Possibly. Here’s some info on using it.

You may also want to post some of the code you’re having trouble with.

You can’t change a string, no matter what you do to it.

All you can do is assign a new string to the variable that refers to the old string.

Yes, poor wording on my part. Here’s what I meant:


var a = "This is some kind of string.",
b = /^.+?s/;
if (b.test(a)) {
    alert("Yeah, it's there.");
    a = a.replace(b, "");
}

When I did a much more complicated version of this, I’d get the alert, but “a” wouldn’t be any different. It turned out the RegExp I was using was wrong (that’s why “replace” wasn’t doing anything), but I still don’t know how it could test, but not replace.

I’d post the code, but after changing both the string and the RegExp, I was finally able to get it to work (at about 1:00 this morning), so I don’t have those exact examples anymore.

What you have there is a fine example of how simplifying the problem and explaining it to someone else, can help you to solve it for yourself.

Well done.