0

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?

1
  • 2
    can you show examples of good/bad strings? Commented Jun 22, 2020 at 15:34

6 Answers 6

5

Just use

/^[a-z-]+$/

Explanation

  • ^ : Match from beginning string.
  • [a-z-] : Match all character between a-z and -.
    • [] : Only characters within brackets are allowed.
    • a-z : Match all character between a-z. Eg: p,s,t.
    • - : Match only strip (-) character.
  • + : The shorthand of {1,}. It's means match 1 or more.
  • $: Match until the end of the string.

Example

const regex= /^[a-z-]+$/

console.log(regex.test("abc")) // true
console.log(regex.test("aBcD")) // false
console.log(regex.test("a-c")) // true

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

var regex = /^[-a-z]+$/;

var regex = /^[-a-z]+$/;
var strs = [
  "a",
  "aB",
  "abcd",
  "abcde-",
  "-",
  "-----",
  "a-b-c",
  "a-D-c",
  " "
];
strs.forEach(str=>console.log(str, regex.test(str)));

1 Comment

This regex can contain spaces unfortunately
0

Try this

/^[a-z-]*$/

it should match the letters a-z or - as many times as possible.

What you regex does is trying to match a-z one single time, followed by any of -, whitespace or dot one single time. Then expect the string to end.

Comments

0

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 /^[a-z\-]*$/. Theres an * instead of + at the end. See Regex Cheat Sheet: https://www.rexegg.com/regex-quickstart.html

Comments

0

I hope this helps

var str = 'asdadWW--asd';

console.log(str.match(/[a-z]|\-/g));

Comments

0

This will work:

var regex = /^[a-z|\-|\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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.