vlina
vlina

Reputation: 81

Regex Javascript escape special characters plus characters limit

Can anyone help me with this regex? I need something which allow: 0-9 a-z A-Z spaces commas hyphens apostrophes and these other special characters: _@=.` plus at the same time set characters limit into it.

I've got this now but it's throwing invalid regular expression exception.

var regex = /^\s*([0-9a-zA-Z\s\,\-\(\)\'\_\@\~\&\*\=\.\`]{1,35}+)\s*$/;
        return this.optional(element) || value.match(regex);
       }, "Please enter a valid name"    );

Thanks for any help!

Upvotes: 0

Views: 338

Answers (2)

zer00ne
zer00ne

Reputation: 44043

Anything Meta Sequence Combo

It looks like you want anything. If so use:

/[\S\s]{1,35}/g

The brackets [...] means one character within it is a match.

\s is any space.

\S is any non-space.

and {1,35} means one to thirty-five consecutive matches of whatever preceded it.

Demo

Features the way to get the first 1 to 35 characters and also every 1 to 35 characters

var str = `1234567~!@#$%^&*e()_+_{}{:>><rthjokyuym.,iul[.<>LOI*&^%$#@!@#$%^&*()_+_{}{:>><KJHBGNJMKL>|}{POIUY~!@#$%^&*(+_)O(IU`;

var rgx = /[\s\S]{1,35}/g;

var res = rgx.exec(str);

console.log(`==== The first 35 characters ===========================`);
console.log(res[0]);
console.log(' ');
console.log(`==== OR for every 1 to 35 characters ===================`);
while (res !== null) {
  console.log(res[0]);
  var res = rgx.exec(str);
}
.as-console-wrapper {
  min-height: 100%;
}

div div div.as-console-row:first-of-type,
div div div.as-console-row:nth-of-type(4) {
  color: tomato
}

Upvotes: 0

FZs
FZs

Reputation: 18619

Remove + after {1,35} and escape only special characters:

var regex = /^\s*([0-9a-zA-Z\s,\-()'_@~&*=.`]{1,35})\s*$/;

console.log(regex.test(" asdfghjkl "))
console.log(regex.test(" asdf'&@() "))
console.log(regex.test(" asdfghjklasdfghjklasdfghjklasdfghjklasdfghjkl "))

Upvotes: 1

Related Questions