I'm trying to write RegExp that match everyting except letters. So far, I've wrote something like this:
/[^a-zA-Z]+/
However, during tests, I've found that it works nicely when I write for example: 'qwe' or 'qqqqqweqwe123123' or something similar, BUT when I start String from number for example: '1qweqwe', it doesn't match.
What do I have to do yet to match everything except letters at any position of my input String?
Thanks in advance.
Edit: Correct RegExp I found is:
/^[^a-zA-Z]*$/
I'm trying to write RegExp that match everyting except letters. So far, I've wrote something like this:
/[^a-zA-Z]+/
However, during tests, I've found that it works nicely when I write for example: 'qwe' or 'qqqqqweqwe123123' or something similar, BUT when I start String from number for example: '1qweqwe', it doesn't match.
What do I have to do yet to match everything except letters at any position of my input String?
Thanks in advance.
Edit: Correct RegExp I found is:
/^[^a-zA-Z]*$/
Share
Improve this question
edited Apr 2, 2013 at 10:30
kmb
asked Apr 2, 2013 at 8:04
kmbkmb
8715 gold badges17 silver badges34 bronze badges
2
-
1
/[^a-zA-Z]+/.test('1qweqwe')
yieldstrue
. – Ja͢ck Commented Apr 2, 2013 at 8:09 - @Jack This solution didn't work for me. I found correct RegExp like this: /^[^a-zA-Z]*$/ – kmb Commented Apr 2, 2013 at 10:31
2 Answers
Reset to default 8What do I have to do yet to match everything except letters at any position of my input String?
You need to use regular expression flags to achieve this
try this
'1qwe2qwe'.match(new RegExp(/[^a-zA-Z]+/g))
it should return ["1", "2"]
the g
flag at end of the regexp tells regexp engine to keep traversing the string after it has found one match. Without g
flag it just abandons traversal upon finding first match. You can find the reference here
Your regular expression is not anchored, so it will yield true
for partial matches. If the whole string should not contain letters:
if (/^[^a-zA-Z]+$/.test(str)) {
// all characters are not alphabetical
}
Or rather, if all characters must be numeric (or empty string):
if (/^\d*$/.test(str)) {
// all characters are digits
}