I have a variable word
that populates with various strings and than becomes an id for a new element. I want to check and make sure the string would make a valid html ID. I came across the regex in this: answer, but I don't know how to put it in an if else statement. This is what I tried:
if (/[A-Za-z][-A-Za-z0-9_:.]*/.test(word) === false)
{
return findIt(i);
}
I tried several of the solutions below and they did work, but not completely. I believe either because of white space or quotes. I am essentially creating an ID out of complete random characters so I'd like regex that only allows alphanumeric strings with no quotes and no white space. Below is a combo of the two that is currently working pretty good but there must be a better answer.
function isValidId(s) {
return /^[^\s]+$/.test(s);
}
if (isValidId(word)===false){
console.log('bad '+word);
return findIt(i);
}
else if(/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(word) === false)
{
console.log(word+" had junk");
return findIt(i);
}