3

I have following function. What this does is filters character that is allowed in a subdomain. In JSLint I got following error. Is there any way I can do this without JSLint showing error. I know I can ignore error in JSLint settings but Is there any other way I can improve my code to not show JSLint error. JSLint Error

function filterSubDomain(value) {
  return value.replace(/[^a-z0-9\-]/ig, '')
    .replace(/^[\-]*/, '')
    .replace(/[\-]*$/, '')
    .toLowerCase();
}
Yalamber
  • 7,360
  • 15
  • 63
  • 89
  • 1
    possible duplicate of [JSLint "insecure ^" in regular expression](http://stackoverflow.com/questions/4109214/jslint-insecure-in-regular-expression) – Pete TNT Jan 23 '15 at 13:00
  • The quick answer is that JSLint doesn't want you saying what you *don't* want in your regex. You need to recompose to say what you *do* so things you haven't thought of don't slip through. That said, I'm having a difficult time figuring out exactly what `filterSubDomain` is doing. **To make this not be a dupe**, can you perhaps tell us specifically what you're looking to do with a "JSLint-compliant" regular expression? I can tell that you're stripping out anything but letters, digits, or a dash in the first, but not absolutely sure what the use case is. Apologies if I'm being thick. – ruffin Jan 23 '15 at 14:49
  • @ruffin I am trying to filter out everything and just get a subdomain friendly string to use it to build hosts for example ```var subdomain = filterSubDomain('xyz!@#$* ')+'.example.com';``` Would produce xyz.example.com – Yalamber Jan 24 '15 at 11:59

1 Answers1

0

I think this is easy enough -- just a quick head rethread. I'll repeat the comment from above quickly: JSLint wants you to say what you do want rather than what you don't, because saying what you don't want always leaves room for a superset of what you do want to sneak in. That is, JSLint's intention is to force you to code explicitly/precisely.

So instead of replace, you want to use match here. Here's one way, I believe (stealing from MDN's match code a little):

/*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, but you get the point. No not's in JavaScript regular expressions with JSLint!

Community
  • 1
  • 1
ruffin
  • 16,507
  • 9
  • 88
  • 138