【发布时间】:2017-03-04 15:27:21
【问题描述】:
有人知道这个 JavaScript 错误来自哪里吗?
SyntaxError: expected expression, got '.'
当使用带有斜线(转义)的正则表达式(如el.href.match(/video\/(.*)@/)[1];)作为字符串传递给 createTextNode、textContent 或 innerHTML 等函数时,我收到此错误。
此正则表达式在不存储为文本时有效。 一个没有斜线的正则表达式作为文本工作,你可以看到我的代码示例:
HTML:
<a style="display: none; width: 840px; height: 472px;" href="http://videos.francetv.fr/video/147338657@Info-web" id="catchup" class="video"></a>
JavaScript:
var el = document.getElementById("catchup");
var script = document.createElement("script");
var text = `
(function() {
var id = el.href.match(/video\/(.*)@/)[1];
alert("test 4 - regex with slash as text: " + id);
})();`;
script.appendChild(document.createTextNode(text));
document.getElementsByTagName("head")[0].appendChild(script);
工作和失败的测试可以在这里找到:
您可以在 GitHub Pages 上对其进行实时测试(JSFiddle 在我的情况下不起作用):
【问题讨论】:
-
您应该将相关代码直接传递给问题(以防您删除 repo),并且正确的链接应该指向特定版本,而不是主分支 - https://github.com/baptx/baptx.github.io/blob/65f11b77df5a7464365374b3505921a4ef9b1272/get_m3u8_debug/get_m3u8_debug.htm
-
@Aprillion 谢谢,我想过在 * 上添加代码,但我希望人们也能看到所有的工作案例。通常我不会删除 repo,但我有想法备份 Wayback Machine 上的链接 web.archive.org/web/20161022102615/https://baptx.github.io/… 特定版本的好点,以防我想修复那里的错误。
标签: javascript regex syntax-error textnode createtextnode