这是我的代码:
/**********************************************************
* 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^\-^_^:^\.]/, ".");
除了对正则表达式的明显更改之外,我建议对函数本身进行以下更改:
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)
如果你喜欢这样的话,请不要投票支持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)
| 归档时间: |
|
| 查看次数: |
1842 次 |
| 最近记录: |