I am looking for a Javascript regex to make sure the string contains only spaces, letters, and ñ — case insensitively.
I already tried: /^[A-Za-z _]*[A-Za-z][A-Za-z _]*$/
but it fails to accept ñ
.
To get a string contains only letters (both uppercase or lowercase) we use a regular expression (/^[A-Za-z]+$/) which allows only letters.
The RegExp \D Metacharacter in JavaScript is used to search non digit characters i.e all the characters except digits. It is same as [^0-9]. Example 1: This example searches the non-digit characters in the whole string.
If you're looking for a space, that would be " " (one space). If you're looking for one or more, it's " *" (that's two spaces and an asterisk) or " +" (one space and a plus).
\W means "non-word characters", the inverse of \w , so it will match spaces as well.
/^[ñA-Za-z _]*[ñA-Za-z][ñA-Za-z _]*$/
and
/^[\u00F1A-Za-z _]*[\u00F1A-Za-z][\u00F1A-Za-z _]*$/
should work.
Javascript regex supports \u0000
through \uFFFF
.
If you simply want that caracter, insert it in the Regex, like [A-Za-zÑñ ]
. Otherwise use a Unicode-knowing Regex library for Javascript like http://xregexp.com/. Sadly JS Regexes don't support Unicode compliant character classes (like \p{L}
in C# regexes)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With