【问题标题】:How to fix JSLint insecure ^ error?如何修复 JSLint 不安全的 ^ 错误?
【发布时间】:2015-03-22 12:36:19
【问题描述】:

我有以下功能。这样做是过滤子域中允许的字符。在 JSLint 我得到以下错误。有什么方法可以在不显示 JSLint 错误的情况下做到这一点。我知道我可以忽略 JSLint 设置中的错误,但是有没有其他方法可以改进我的代码以不显示 JSLint 错误。

function filterSubDomain(value) {
  return value.replace(/[^a-z0-9\-]/ig, '')
    .replace(/^[\-]*/, '')
    .replace(/[\-]*$/, '')
    .toLowerCase();
}

【问题讨论】:

  • 快速回答是 JSLint 不希望你在你的正则表达式中说出你不想想要的东西。你需要重新组合来说出你做什么,这样你没有想到的事情就不会溜走。也就是说,我很难弄清楚filterSubDomain 在做什么。 为了避免被骗,您能否具体告诉我们您希望如何使用“符合 JSLint”的正则表达式?我可以告诉您,您首先要删除除字母、数字或破折号之外的任何内容,但不能绝对确定用例是什么。抱歉,如果我太厚了。
  • @ruffin 我正在尝试过滤掉所有内容,只获取一个子域友好字符串以使用它来构建主机,例如 var subdomain = filterSubDomain('xyz!@#$* ')+'.example.com'; 会产生 xyz.example.com

标签: jslint


【解决方案1】:

我认为这很容易——只需快速重新线程即可。我将快速重复上面的评论:JSLint 希望你说出你想要而不是不想,因为说你不想要的总是为你想要潜入的超集留出空间。也就是说,JSLint 的目的是强迫你显式/精确地编码。

所以你想在这里使用match 而不是replace。这是一种方法,我相信(从MDN's match code 窃取一点):

/*jslint sloppy:true, white:true, devel:true */
function filterSubDomain(value) {
    var out = value,
        re = /[a-z0-9\-]+/gi,
        found;

    found = value.match(re);

    out = found.join("");

    // There are better ways to `trim('-')`.
    while (0 === out.indexOf("-")) {
        out = out.substr(1);
    }
    while (out.length === out.lastIndexOf("-")+1) {
        out = out.slice(0,out.length-1);
    }

    return out;
}

console.log(filterSubDomain('---For more inform--ation, - see Chapter 3.4.5.1---'));
// Formoreinform--ation-seeChapter3451

There are other ways to trim,但你明白了。不,不是在带有 JSLint 的 JavaScript 正则表达式中!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-23
    • 2015-05-15
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 2015-02-09
    • 2020-12-18
    • 2012-08-11
    相关资源
    最近更新 更多