I want to match a string to make sure it contains only letters.
I\'ve got this and it works just fine:
var onlyLetters = /^[a-zA-Z]*$/.test(myString)
You could use a blacklist - a list of characters to exclude.
Also, it is important to verify the input on server-side, not only on client-side! Client-side can be bypassed easily.
This can be tricky, unfortunately JavaScript has pretty poor support for internationalization. To do this check you'll have to create your own character class. This is because for instance, \w
is the same as [0-9A-Z_a-z]
which won't help you much and there isn't anything like [[:alpha:]]
in Javascript. But since it sounds like you're only going to use one other langauge you can probably just add those other characters into your character class.
By the way, I think you'll need a ?
or *
in your regexp there if myString can be longer than one character.
The full example,
/^[a-zA-Zéüöêåø]*$/.test(myString);
There are some shortcuts to achive this in other regular expression dialects - see this page. But I don't believe there are any standardised ones in JavaScript - certainly not that would be supported by all browsers.
There should be, but the regex will be localization dependent. Thus, é ü ö ê å ø
won't be filtered if you're on a US localization, for example. To ensure your web site does what you want across all localizations, you should explicitly write out the characters in a form similar to what you are already doing.
The only standard one I am aware of though is \w
, which would match all alphanumeric characters. You could do it the "standard" way by running two regex, one to verify \w
matches and another to verify that \d
(all digits) does not match, which would result in a guaranteed alpha-only string. Again, I'd strongly urge you not to use this technique as there's no guarantee what \w
will represent in a given localization, but this does answer your question.
You could aways use a blacklist instead of a whitelist. That way you only remove the characters you do not need.
var regexp = /\B\#[a-zA-Z\x7f-\xff]+/g;
var result = searchText.match(regexp);