0

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');
});
Dev Ops
  • 96
  • 8

1 Answers1

1

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');
});
Thanh Trung
  • 3,566
  • 3
  • 31
  • 42
  • Thanks, my idea for the parenthesis was to capture one word as a group, suppose it was overkill, appreciate it.. – Dev Ops Apr 22 '18 at 15:47
  • @DevOps note that regex is not enough to validate a complex html string `
    abc er><><>>`. If you want to do this try another approach.
    – Thanh Trung Apr 22 '18 at 15:56
  • Hi Thanh, this was the second check after I evaluate a string that might contain and tag type elements, so it is still valid and will allow me to create a valid element with document.createElement('div') for example. What you made me realise now though is that my check for valid html is too simplistic. I am using the regex **/^<[a-z][\s\S]*>/g** to check for html tags, but your complex string fails this test... so now to re-eval that regex. Thank you for pointing this out. – Dev Ops Apr 22 '18 at 16:55
  • https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags?noredirect=1&lq=1 – Thanh Trung Apr 22 '18 at 18:23