1

I am working on regexp where if the user enter consecutive spaces, dashes, apostrophes then I have to show one error message

^[a-zA-Z0-9!@#\$%\^\&*\)\(+=._-]{0,}$

With the above reg exp I am getting if the user enter one dashes I am getting error but here I want spaces apostrophes.

3

1 Answer 1

1

If I understood correctly, basically you have to do Back-referencing in order to check for double words (or more than doubles)

/(\s-,)\1+/.test(...)

const hasDoubles = new RegExp(/(\s|-|,)\1+/);

console.log( hasDoubles.test("hello - ") ) // false
console.log( hasDoubles.test("--") ) // true
console.log( hasDoubles.test("  ") ) // true
console.log( hasDoubles.test(",,") ) // true

This code captures any space \s or dashes - or , then checks if it occurs again 1 or more times denoted by \1+ the \1 for back-referencing the capture group, and + for 1 or more occurances.

Sign up to request clarification or add additional context in comments.

6 Comments

thanks for the quick answer but when i try in regex online i am not getting the result let say for exmple if i am typing consecutive ----- or spaces or """""""
can you send me a link? because i tried an online solution and all the consecutive cases match(or the console). ------- does match it all for example.
youre missing a ( in the beginning, here a working link regex101.com/r/F0bK6X/3
also you didnt mention quotes, you said apostrophes. anyways, here is another link with double quotes check, you can add whatever you want if you got the pattern regex101.com/r/F0bK6X/4
Thanks for your help but this was not considering space how to include space for this
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.