[英]Unescaped '^' with jslint
This is my code: 这是我的代码:
/********************************************************** * remove non-standard characters to give a valid html id * **********************************************************/ function htmlid(s) { return s.gsub(/[^A-Z^a-z^0-9^\-^_^:^\.]/, "."); }
Why does jslint throw this error? 为什么jslint会抛出此错误?
Lint at line 5 character 25: Unescaped '^'. return s.gsub(/[^A-Z^a-z^0-9^\-^_^:^\.]/, ".");
Apart from the obvious change to the regex, 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;
}
Don't vote for this...vote for Tomalak's answer if you like this (it is the same as his but without using arguments.callee plus caching the regex itself). 如果你喜欢这样的话,请不要投票支持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;
};
}());
如果你打算拥有的是一个否定的角色类,那么这就是你想要的:
return s.gsub(/[^A-Za-z0-9_:.-]/, ".");
First of all, thank you for the answers. 首先,谢谢你的答案。 Your brought a little error to the semantic of the function, as it should return the same id if I query for the same string twice.
你给函数的语义带来了一点错误,因为如果我查询两次相同的字符串,它应该返回相同的id。 Eg:
例如:
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"
Howvere, I adopted your functions to: 多哈,我采用了你的职能:
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;
};
}());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.