Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does '-$1' mean in javascript?

Tags:

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;
    }
like image 533
tarabyte Avatar asked Mar 13 '26 04:03

tarabyte


1 Answers

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" 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.

like image 185
T.J. Crowder Avatar answered Mar 15 '26 18:03

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!