Reputation: 232
This should automatically remove characters NOT on my regex, but if I put in the string asdf sd %$##$
, it doesnt remove anything, and if I put in this #sdf%#
, it only removes the first character. I'm trying to make it remove any and all instances of those symbols/special characters (anything not on my regex), but its not working all the time. Thanks for any help:
function ohno(){
var pattern = new RegExp("[^a-zA-Z0-9]+");
var str = "#sdf%#"; //"asdf sd %$##$" // Try both
str = str.replace(pattern,' ');
document.getElementById('msg').innerHTML = str;
}
Upvotes: 1
Views: 548
Reputation: 133453
You need to set global using "g"
, The flag indicates that the regular expression should be tested against all possible matches in a string.
new RegExp("[^a-zA-Z0-9]+", "g")
var pattern = new RegExp("[^a-zA-Z0-9]+", "g");
var str = "#sdf%#"; //"asdf sd %$##$" // Try both
str = str.replace(pattern,' ');
alert(str)
Upvotes: 4
Reputation: 382474
You need the g flag to remove more than one match:
var pattern = new RegExp("[^a-zA-Z0-9]+", "g");
Note that it would be more efficient and readable to use a regex literal instead of the RegExp constructor:
var pattern = /[^a-zA-Z0-9]+/g;
Upvotes: 4