Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing any character besides 0-9 + - / * and ^ [duplicate]

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.

like image 569
zdombie Avatar asked Dec 26 '22 12:12

zdombie


1 Answers

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, '');
like image 183
Mark Byers Avatar answered Jan 18 '23 07:01

Mark Byers