Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex to accept only letters, spaces, and ñ

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 ñ.

like image 676
Jonathan Edgardo Avatar asked Sep 10 '11 16:09

Jonathan Edgardo


People also ask

How do you regex only letters?

To get a string contains only letters (both uppercase or lowercase) we use a regular expression (/^[A-Za-z]+$/) which allows only letters.

What is \d in JavaScript regex?

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.

How do you match a space in regex?

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).

Does \w include spaces regex?

\W means "non-word characters", the inverse of \w , so it will match spaces as well.


2 Answers

/^[ñ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.

like image 114
Benjamin Udink ten Cate Avatar answered Sep 28 '22 07:09

Benjamin Udink ten Cate


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)

like image 31
xanatos Avatar answered Sep 28 '22 08:09

xanatos