admin管理员组

文章数量:1336293

I'm trying to figure out what the assignment to id means in the following snippet, and in particular the '-$1'. I do see that it's taking the DOM element text and swapping in something else, and then lowercasing the result. I just don't understand what is being swapped in.

   for (var k in ui) {
      var id = k.replace(/([A-Z])/, '-$1').toLowerCase();
      var element = document.getElementById(id);
      if (!element) {
        throw "Missing UI element: " + k;
      }
      ui[k] = element;
    }

I'm trying to figure out what the assignment to id means in the following snippet, and in particular the '-$1'. I do see that it's taking the DOM element text and swapping in something else, and then lowercasing the result. I just don't understand what is being swapped in.

   for (var k in ui) {
      var id = k.replace(/([A-Z])/, '-$1').toLowerCase();
      var element = document.getElementById(id);
      if (!element) {
        throw "Missing UI element: " + k;
      }
      ui[k] = element;
    }
Share Improve this question asked Jul 25, 2014 at 22:09 tarabytetarabyte 19.2k16 gold badges85 silver badges126 bronze badges 3
  • 1 developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – Felix Kling Commented Jul 25, 2014 at 22:11
  • Duplicate? What does $1, $2, etc. mean in Regular Expressions? – Felix Kling Commented Jul 25, 2014 at 22:13
  • 2 Downvotes seem harsh. – T.J. Crowder Commented Jul 25, 2014 at 22:17
Add a ment  | 

1 Answer 1

Reset to default 9

What does '-$1' mean in javascript?

Nothing. But $1 in a replace replacement string refers to the first capture group, saying "include the first capture group in the replacement here." The - is literal text to include in the replacement.

var id = k.replace(/([A-Z])/, '-$1').toLowerCase();
// Capture group    ^     ^

What that call does is replace the first upper-case letter in the English alphabet (A-Z) with a dash followed by the character (and then the .toLowerCase() after it turns the string to all lower-case). E.g., "testingABC" bees "testing-abc". (It's only the first upper-case letter because there's no "global" [g] flag on the regular expression.)

In this particular case, the code doesn't need to use a capture group, it could be this:

var id = k.replace(/[A-Z]/, '-$&').toLowerCase()

$& refers to the entire match.

本文标签: What does 39139 mean in javascriptStack Overflow