What does '-$1' mean in javascript? - Stack Overflow

I'm trying to figure out what the assignment to id means in the following snippet, and in particul

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742405562a4437775.html

相关推荐

  • What does '-$1' mean in javascript? - Stack Overflow

    I'm trying to figure out what the assignment to id means in the following snippet, and in particul

    4小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信