4

I'm trying to further my understanding of regular expressions in JavaScript.

So I have a form that allows a user to provide any string of characters. I'd like to take that string and remove any character that isn't a number, parenthesis, +, -, *, /, or ^. I'm trying to write a negating regex to grab anything that isn't valid and remove it. So far the code concerning this issue looks like this:

var pattern = /[^-\+\(\)\*\/\^0-9]*/g;
function validate (form) {
    var string = form.input.value;
    string.replace(pattern, '');
    alert(string);
};

This regex works as intended on http://www.infobyip.com/regularexpressioncalculator.php regex tester, but always alerts with the exact string I supply without making any changes in the calculator. Any advice or pointers would be greatly appreciated.

zdombie
  • 41
  • 2
  • 3
    You don't need to escape everything inside of a character set: `/[^-+()^*\/0-9]/g`. – Blender Dec 24 '12 at 00:05
  • @Blender: You do need to escape that forward slash inside of a regular expression, though. (And although I suppose it’s probably for clarity, the `^` doesn’t need escaping either.) – Ry- Dec 24 '12 at 00:06
  • 1
    @minitech: Oddly enough, that didn't trouble the JS regex engine. Thanks. – Blender Dec 24 '12 at 00:07
  • 1
    @minitech: Actually I was wondering the same thing, but I tried it in Chrome and it worked just fine without any escaping. – Mark Byers Dec 24 '12 at 00:07
  • @MarkByers: Really? Fancy that, I thought it was just a problem in VIM. I guess JavaScript’s regular expressions are smarter than they let on :) – Ry- Dec 24 '12 at 00:07

1 Answers1

10

The replace method doesn't modify the string. It creates a new string with the result of the replacement and returns it. You need to assign the result of the replacement back to the variable:

string = string.replace(pattern, '');
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452