我有:
window.page="home";
document.getElementsByTagName("title")[0].innerHTML=
"hello.com | $page".replace(/\$([^\s]*)/g,window["$1"]);
想法是得到:
<title>hello.com | home</title>
但我反而得到:
<title>hello.com | undefined</title>
当我执行以下操作时:
document.getElementsByTagName("title")[0].innerHTML=
"hello.com | $page".replace(/\$([^\s]*)/g,"$1");
我得到:
<title>hello.com | page</title>
这是因为该函数将 "$1"
作为映射其输出的参数。我想知道是否有办法使用捕获组来访问数组/对象?
最佳答案
您不能使用只能将字符串替换模式的一部分用作参数的反向引用。您需要使用 replace callback为此。
使用
.replace(/\$(\S*)/g, function($0,$1) {return window[$1];})
请注意 \S
(非空白)比 [^\s]
(非空白)短。
function($0,$1)
中,$0
代表整场比赛,$1
代表第1组内容。
关于javascript - 使用正则表达式匹配访问数组/对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45270163/