0

In my program , i want to validate id of html tags.. To my functions id is passed as a string preceeding with #.. I found that ,rules for naming and id in HTML are,

  • Must begin with a letter A-Z or a-z
  • Can be followed by: letters (A-Za-z), digits (0-9), hyphens ("-"), and underscores ("_") So i written the following regular expression.

    /(^|\s)(#{1})([a-zA-Z])([^a-zA-Z0-9]{0})/g;

But it is giving me wrong results.What's wrong with my regular expression?

3
  • 2
    What results do you get? Could you provide some sample input and corresponding output? Commented Apr 30, 2012 at 22:01
  • Note that many of these restrictions have been removed in html 5. Commented Apr 30, 2012 at 22:02
  • mathiasbynens.be/notes/html5-id-class ya got it.... Commented Apr 30, 2012 at 22:10

2 Answers 2

2
/#[a-z][\w\d-]*\b/gi
  • \w signifies letters from a-z, A-Z and underscore (_)
  • \d signifies whole numbers from 0-9
  • \b signifies a word boundary
  • the i flag is to catch the first letter regardless of case

EDIT: Sorry for forgetting the boundary in the beginning of the group.

var str = '#sss #s23 dd#ww';
// #ww will be omitted because # is not the
// first char in the char group there.
var rx = /(^|\s)(#[a-z][\w\d-]*)\b/gi;
var arr = [];
str.replace(rx, function(){arr.push(arguments[2])});
// this is just to catch the id's.
// it won't modify str.
for (var i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

try:

/^#[a-z]{1}[a-z0-9_-]*$/i

4 Comments

this gives me correct result..but [a-z0-9_-] same as [^a-z0-9_-]{0}?. then why am i getting wrong results?
@JinuJD: no, oblivious not the same
Your solution with {0} is completly different from mine. I must say i struggle to understand what is the possibile result with your regex
it should contain zero occurances of non alphanumeric_- at the end which is same as alphanumeric_- characters at the end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.