Reputation: 243
I'm aiming to create a regex that allows alphanumerics and any special characters.
Example of accepted words:
Test 1
Test 123 !#@#
But it shouldn't accept characters that have spaces before or after the word, or also multiple spaces, or only whitespace.
Example of unaccepted words:
Test 1 - spaces before
Test 1 - multiple spaces between
Test(spaces) - spaces after
(only spaces) - only spaces
Upvotes: 0
Views: 831
Reputation:
Instead of using a regexp, you can split
the string on spaces, then use every
to make sure there are no null strings in the result (which would mean that there were extra spaces either at the beginning or end or in between words somewhere).
const tests = ['Test 1', ' Test 1', 'Test 123 !#@#', 'Test 1', 'Test ', ' '];
const passes = str => str . split(' ') . every(Boolean);
document.getElementById('results').textContent =
tests.map(str => `'${str}': ${passes(str)}`) . join('\n');
<div id="results" style="white-space: pre; font-family: monospace; "></div>
How does this every(Boolean)
work? It converts each element to a boolean true/false value, and makes sure that they all convert to true. In JS, an empty string will convert to false, so this checks that each element is not an empty string.
Upvotes: 2
Reputation: 1041
What about :
^[^ ]+( [^ ])*$
Please escape the special characters accordingly to the language you will use for your regex.
Upvotes: 1