简体   繁体   中英

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; } 

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

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM