Javascript Regex Whitelist with character limit
-
13-06-2021 - |
سؤال
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?
المحلول
str = str.replace(/[^A-Za-z-_0-9\s]/g, "").substring(0,10); //At most 10 chars
نصائح أخرى
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, "");
لا تنتمي إلى StackOverflow