Zapp
Zapp

Reputation: 232

javascript regex Numbers and letters only

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

Answers (2)

Satpal
Satpal

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")

Reference

var pattern = new RegExp("[^a-zA-Z0-9]+", "g");
var str = "#sdf%#"; //"asdf sd %$##$" // Try both


str = str.replace(pattern,' ');
alert(str)

Upvotes: 4

Denys Séguret
Denys Séguret

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;

reference

Upvotes: 4

Related Questions