用jslint取消转义'^'

Ben*_*Ben 2 javascript jslint

这是我的代码:


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

为什么jslint会抛出此错误?

Lint at line 5 character 25: Unescaped '^'.
return s.gsub(/[^A-Z^a-z^0-9^\-^_^:^\.]/, ".");

Tom*_*lak 5

除了对正则表达式的明显更改之外,我建议对函数本身进行以下更改:

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;
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*och 5

如果你喜欢这样的话,请不要投票支持Tomalak的答案(它与他的相同,但没有使用arguments.callee加上缓存正则表达式本身).

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;
    };
}());
Run Code Online (Sandbox Code Playgroud)

  • 用封闭来优化我的版本的+1 :-)我不想让它比必要更复杂,因为我已经偏离了原来的问题,但这当然更有效率. (2认同)