Squirrl
Squirrl

Reputation: 4966

How do I check if a string would make a valid html ID using JS?

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);
    }

Upvotes: 1

Views: 2775

Answers (3)

Roland
Roland

Reputation: 9721

I use this little snippet:

function (selector) {
    return /^(?:#([\w-]+))$/.exec(selector)[1];
}

It's going to return null if your string is not a valid id or it will return the id without the hash (it will allow you to directly do a document.getElementById()).

Source: sizzlejs.

Upvotes: 0

RobG
RobG

Reputation: 147493

In HTML5, the only restriction on the ID attribute value is that it contain at least one character and not contain any whitespace, so the following should do the job:

function isValidId(s) {
  return /^[^\s]+$/.test(s);
}

Upvotes: 1

mishik
mishik

Reputation: 10003

Result of test() call is already sufficient:

if (/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(word)) {
    return findIt(i);
} else {
    // Does not match
}

Upvotes: 2

Related Questions