Dev Ops
Dev Ops

Reputation: 96

Javascript regex test again a single string that has no special character or spaces

I am writing a function wrapper for document.createElement() in which I can pass in either a element tag name eg. 'div' or pass in a complete html string to be created. I have the regex for testing for html tag starts and ends i.e. '<' or '>', but now i want to further test the string for no special characters.

I have /^([a-zA-Z]*)?$/g to test a match against, but it is failing on a blank string. I thought the + would capture this, but seems not. Suppose I can test for empty string before, but was wondering if there's a way to test for this.

var strings = ["div","<div>...</div>","div1","1div","div-","[div]","(div)","$div",""];

strings.forEach(function(str, i) {
  /^([a-zA-Z]+)?$/.test(str)
    ? console.log(i, 'OK valid')
    : console.log(i, 'XX invalid');
});

var re = new RegExp('^([a-zA-Z]+)?$','g'); 
strings.forEach(function(str, i) {
  re.test(str)
    ? console.log(i, 'OK valid')
    : console.log(i, 'XX invalid');
});

Upvotes: 0

Views: 166

Answers (1)

Thanh Trung
Thanh Trung

Reputation: 3804

Not sure what all the parenthesis is for but changing ? to + should be enough

var strings = ["div","<div>...</div>","div1","1div","div-","[div]","(div)","$div",""];

strings.forEach(function(str, i) {
  /^[a-zA-Z]+$/.test(str)
    ? console.log(i, 'OK valid')
    : console.log(i, 'XX invalid');
});

var re = new RegExp('^[a-zA-Z]+$','g'); 
strings.forEach(function(str, i) {
  re.test(str)
    ? console.log(i, 'OK valid')
    : console.log(i, 'XX invalid');
});

Upvotes: 1

Related Questions