Elvira
Elvira

Reputation: 1440

Regex for alphabetic numeric and - '

I've been trying out different regexes but I can't seem to find the correct one.

I need an regex which allows users to type alphabetic, digits, spaces, - and ' in texts.

So strings like: "'s Ochtends vroeg" "tomorrow-night" "ISBN1234ABC"

should be true.

I've tried the following regexes with the following code:

/([A-Za-z0-9'-\s])/g
[^#$@_&!*()]
and more of these variations

   var regex = new RegExp("([a-zA-Z0-9\s'-])+");
   console.log(regex.test(word));

All return true now, when I type in the word: "ABN##@@123-TEST". It should be false because the characters ##@@ are in it.

Thanks for your help.

Upvotes: 2

Views: 304

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

The new RegExp("([a-zA-Z0-9\s'-])+") regex finds partial matches, i.e. it finds streaks of letters, digits, ' or - inside a larger string, and will return the match once found. NOTE it does not find whitespace, because \s inside a string literal gets parsed as a letter s, not \s whitespace pattern.

So, you need to do 2 things:

  • Add anchors, ^ at the start and $ at the end of the pattern to ensure a whole string match
  • Use a regex literal notation, /regex/, to ensure \s is parsed as a whitespace pattern.

Note you do not need to wrap the whole pattern within a capturing group, you can always access the whole regex match value (even when replacing, with $& backreference). So, you may remove ( and ) around the pattern.

Thus, your solution is

var regex = /^[a-zA-Z0-9\s'-]+$/;

JS demo:

function test() {
  var str = document.getElementById("text").value;
  var regex = /^[a-zA-Z0-9\s'-]+$/;
  if (regex.test(str)) {
     console.log("Valid");
  }
  else {
     console.log("Not Valid");
  }
}
<input id="text" type="text" />
<button id="btn" onclick="test()">Test</button>

Upvotes: 2

Related Questions