From your example checking for an "empty" string, it's clear you want to ignore whitespace at the beginning or end.
The simplest way to do this, if you don't actually have a regex requirement, is just trim
and check the length:
str = str.trim();
if (str.length && str.length <= 500) {
// All good
}
But if you need a regex (perhaps an HTML5 validation regex), then it's simply a matter of saying 1. "ignore whitespace at the beginning, 2. require 1-500 characters in the middle, and 3. ignore whitespace at the end." (with anchors to ensure we're matching the full string):
// 111 333
// ---------vvv----------vvv
var rex = /^\s*\S.{0,499}\s*$/;
// ------------^^^^^^^^^^
// 2222222222
Note the \S
which requires at least one non-whitespace character there, followed by 0 to 499 other characters.
Note: You'll need to trim
the string at some point, though, since the whitespace at one end of the other can take you over the 500 limit.
Example usage:
// NOTE: Using 5 instead of 500 to make tests shorter
var rex = /^\s*\S.{0,4}\s*$/;
console.log(rex.test("")); // false
console.log(rex.test("a")); // true
console.log(rex.test(" a ")); // true
console.log(rex.test(" 12345 ")); // true
console.log(rex.test(" 123456 ")); // false
console.log(rex.test("123456")); // false
console.log(rex.test("1234 ")); // true
console.log(rex.test(" ")); // false
.as-console-wrapper {
max-height: 100% !important;
}
Note: In JavaScript, .
doesn't match line termination characters. If you want to allow those, use [\w\W]
(anything that's a word character or not a word character) instead of .
: /^\s*[\w\W]{1,500}\s*$/