简体   繁体   中英

What does '-$1' mean in javascript?

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;
    }

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 ( AZ ) with a dash followed by the character (and then the .toLowerCase() after it turns the string to all lower-case). Eg, "testingABC" becomes "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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM