Unescaped '^' with jslint

This is my code:

/ ************************************************ *********
 * remove non-standard characters to give a valid html id *
 ************************************************* ******** /
function htmlid (s) {
 return s.gsub (/ [^ AZ ^ az ^ 0-9 ^ \ - ^ _ ^: ^ \.] /, ".");
}

Why is jslint throwing this error?

Lint at line 5 character 25: Unescaped '^'.
return s.gsub (/ [^ AZ ^ az ^ 0-9 ^ \ - ^ _ ^: ^ \.] /, ".");
+2


a source to share


4 answers


Apart from the obvious change to the regular expression, I recommend the following change to the function itself:



function htmlid(s) {
  // prevents duplicate IDs by remembering all IDs created (+ a counter)
  var self = arguments.callee;
  if (!self.cache) self.cache = {};

  var id = s.replace(/[^A-Za-z0-9_:.-]/, "."); // note the dash is at the end!
  if (id in self.cache) id += self.cache[id]++;
  self.cache[id] = 0;

  return id;
}

      

+5


a source


Don't vote for this ... vote for Tomalak if you like it (this is the same as his, but without using arguments.callee plus caching the regex itself).



var htmlid = (function(){
    var cache = {},
        reg = /[^A-Za-z0-9_:.-]/;
    return function(s){
        var id = s.replace(reg, ".");
        if (id in cache){ id += cache[id]++;}
        cache[id] = 0;

        return id;
    };
}());

      

+5


a source


If what you intend to have is a negative character class, then this is what you want:

return s.gsub(/[^A-Za-z0-9_:.-]/, ".");

      

+2


a source


First of all, thanks for the answers. You brought in a small error in the semantics of the function, as it must return the same identifier if I ask for the same string twice. For instance:.

htmlid("foo bar");  // -> "foo.bar"
htmlid("foo bar");  // -> "foo.bar"
htmlid("foo.bar");  // -> "foo.bar0"
htmlid("foo.bar0"); // -> "foo.bar00"
htmlid("foo.bar");  // -> "foo.bar0"

      

Anyway, I accepted your functions:

var htmlid = (function () {
    var cache = {},
        ncache = {},
        reg = /[^A-Za-z0-9_:.-]/;
    return function (s) {
        var id;
        if (s in cache) {
            id = cache[s];
        } else {
            id = s.replace(reg,".");
            if (id in ncache) {
                id += ncache[id]++;
            }
            ncache[id] = 0;
            cache[s] = id;
        }
        return id;
    };
}());

      

+1


a source







All Articles