Javascript Regex Whitelist with character limit
-
13-06-2021 - |
Question
I'm trying to add a character limit clause to this white list regex approach
str = str.replace(/[^A-Za-z-_0-9 ]/g, "");
Is it possible and how do I do it?
Solution
str = str.replace(/[^A-Za-z-_0-9\s]/g, "").substring(0,10); //At most 10 chars
OTHER TIPS
Use a quantifier to specify the limit.
If you want a maximum (10 for example) do this:
str = str.replace(/[^A-Za-z-_0-9 ]{,10}/g, "");
A minimum:
str = str.replace(/[^A-Za-z-_0-9 ]{10,}/g, "");
A range:
str = str.replace(/[^A-Za-z-_0-9 ]{8,10}/g, "");
An exact quantity:
str = str.replace(/[^A-Za-z-_0-9 ]{10}/g, "");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow