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
1 Answer
Reset to default 9What 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
版权声明:本文标题:What does '-$1' mean in javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742405562a2468748.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论