I don't know how to create a regular expression in JavaScript or jQuery.
I want to create a regular expression that will check if a string contains only characters between a-z and A-Z with any arrangement.
EDIT
When I tried to make regex
/^[a-zA-Z\s]+$/
to accept white spaces as well. It is not working. What could be the mistake?
I am testing my regular expression at JavaScript RegExp Example: Online Regular Expression Tester.
You can use this regex /^[ A-Za-z0-9_@./#&+-]*$/.
A regex consists of a sequence of characters, metacharacters (such as . , \d , \D , \ s, \S , \w , \W ) and operators (such as + , * , ? , | , ^ ). They are constructed by combining many smaller sub-expressions.
The regular expression [A-Z][a-z]* matches any sequence of letters that starts with an uppercase letter and is followed by zero or more lowercase letters. The special character * after the closing square bracket specifies to match zero or more occurrences of the character set.
You can use regular expressions to achieve this task. In order to verify that the string only contains letters, numbers, underscores and dashes, we can use the following regex: "^[A-Za-z0-9_-]*$".
/^[a-zA-Z]*$/
Change the *
to +
if you don't want to allow empty matches.
Character classes ([...]
), Anchors (^
and $
), Repetition (+
, *
)
The /
are just delimiters, it denotes the start and the end of the regex. One use of this is now you can use modifiers on it.
Piggybacking on what the other answers say, since you don't know how to do them at all, here's an example of how you might do it in JavaScript:
var charactersOnly = "This contains only characters";
var nonCharacters = "This has _@#*($()*@#$(*@%^_(#@!$ non-characters";
if (charactersOnly.search(/[^a-zA-Z]+/) === -1) {
alert("Only characters");
}
if (nonCharacters.search(/[^a-zA-Z]+/)) {
alert("There are non characters.");
}
The /
starting and ending the regular expression signify that it's a regular expression. The search
function takes both strings and regexes, so the /
are necessary to specify a regex.
From the MDN Docs, the function returns -1
if there is no match.
Also note: that this works for only a-z, A-Z. If there are spaces, it will fail.
/^[a-zA-Z]+$/
Off the top of my head.
Edit:
Or if you don't like the weird looking literal syntax you can do it like this
new RegExp("^[a-zA-Z]+$");
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