I needed to create a method that would sanitize DOM IDs based on the HTML 4 criteria (yeah, HTML 5 is a lot looser). Does this make sense? Did I get too cute with making it concise? Am I totally misinterpreting what a DOM id is? I presumed it meant something like <p id=annoying_paragraph></p>.def sanitize_dom_id(candidate_id)  #The HTML 4.01 spec states that ID tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]),   #hyphens (-), underscores (_), colons (:), and periods (.).  prefix = candidate_id.slice!(0)  #replace invalid prefix with Z_  prefix = Z_ if [/[a-zA-Z]/].nil?   #replace invalid internal characters with underscore _  candidate_id.gsub!(/[^a-zA-Z0-9\.:_-]/,_)  #{prefix}#{candidate_id}endSample input and output:sanitize_dom_id(1htmlid)Should result with Z_htmlidsanitize_dom_id(html id)Should result with html_id
Sanitize DOM IDs
ruby;html;ruby on rails;regex;dom
Here is my implementation, the early return and extra variable are probably a matter of taste. That early return doesn't feel idiomatic.It attempts to remove invalid characters at the start of the candidate_id, until it finds valid ones. It will only prefix if it can't find a valid id somewhere in the candidate.def sanitize_dom_id(candidate_id)  # Replace non-ascii chars with an ascii version  # See ActiveSupport::Inflector#transliterate  sanitized_id = transliterate(candidate_id)  # Replace invalid characters with underscore _  sanitized_id.gsub!(/[^a-zA-Z0-9\.:_-]/,_)  # Remove invalid (non Alpha) leading characters   valid_id = sanitized_id.gsub(/^[^a-zA-Z]+/, '')  return valid_id unless valid_id.empty?  # Prefix the ID with a known valid prefix.  n_ + sanitized_idendExample output.100-1012foo foo-bar f-=-=- ba9 --dash 9999 66-66.split.map {|id| sanitize_dom_id id }>> [foo, foo-bar, f-_-_-, ba9, dash, n9999, n66-66]