I want to have a regular expression in JavaScript which help me to validate a string with contains only lower case character and and this character -
.
I use this expression:
var regex = /^[a-z][-\s\.]$/
It doesn't work. Any idea?
Simple, just use: /^[az-]+$/
Explanation:
^
: Match from beginning string [az-]
: Match all character between az and -
[]
: Only characters within brackets are allowed az
: Match all character between az. Ex: p,s,t-
: Match only strip ( -
) character +
: Shorthand for {1,}
. The means is match 1 or more$
: Match until end of the string Example:
const regex= /^[az-]+$/ console.log(regex.test("abc")) // true console.log(regex.test("aBcD")) // false console.log(regex.test("ac")) // true
Try this:
var regex = /^[-a-z]+$/;
var regex = /^[-az]+$/; var strs = [ "a", "aB", "abcd", "abcde-", "-", "-----", "abc", "aDc", " " ]; strs.forEach(str=>console.log(str, regex.test(str)));
Try this
/^[a-z-]*$/
it should match the letters az or - as many times as possible.
What you regex does is trying to match az one single time, followed by any of -, whitespace or dot one single time. Then expect the string to end.
Use this regular expression:
let regex = /^[a-z\-]+$/;
Then:
regex.test("abcd") // true
regex.test("ab-d") // true
regex.test("ab3d") // false
regex.test("") // false
PS: If you want to allow empty string ""
to pass, use /^[az\-]*$/
. Theres an *
instead of +
at the end. See Regex Cheat Sheet: https://www.rexegg.com/regex-quickstart.html
This will work:
var regex = /^[az|\-|\s]+$/ //For this regex make use of the 'or' | operator str = 'test- '; str.match(regex); //["test- ", index: 0, input: "test- ", groups: undefined] str = 'testT- ' // string now contains an Uppercase Letter so it shouldn't match anymore str.match(regex) //null
I hope this helps
var str = 'asdadWW--asd'; console.log(str.match(/[az]|\-/g));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.