1

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?

shiva8
  • 2,142
  • 2
  • 19
  • 24
  • I'm unsure of what you want to do, exactly. Can you provide an example string and describe your desired behavior? I'm guessing you want to limit the length of the whole string, or you want to match only runs of matched characters that exceed (or are under) a certain length. – apsillers Jun 08 '12 at 05:10
  • For example, suppose you have a limit of 10: for the string "aaa%$?!@^&*()~`bbb" should the run of twelve invalid characters in the middle *not* be removed because there is more than 10 matched characters there? – apsillers Jun 08 '12 at 05:27

2 Answers2

3

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, "");
Paul
  • 139,544
  • 27
  • 275
  • 264
  • 2
    I tried this solution, it didn't work, which is why I came here :(. tag = tag.replace(/[^A-Za-z-_0-9 ]{0,5}/g, ""); Although that still whitelist the characters properly, it doesn't enforce the character limit to the string – shiva8 Jun 08 '12 at 05:00
0
str = str.replace(/[^A-Za-z-_0-9\s]/g, "").substring(0,10);  //At most 10 chars
Bart
  • 19,692
  • 7
  • 68
  • 77
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • 1
    Came out with the answer before you did, but thanks this works. Sometimes simple solutions are the best :D – shiva8 Jun 08 '12 at 20:01