有人知道这个 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 在我的案例中不起作用):
最佳答案
您正在转义正斜杠而不是反斜杠。
`el.href.match(/video\/(.*)@/)[1]` === 'el.href.match(/video/(.*)@/)[1]'
// '\/' == '/', not '\\/'
您还需要转义反斜杠:
`el.href.match(/video\\/(.*)@/)[1]`
您还可以利用带有 string representation of a regex 的模板字符串获取它的源代码表示。基本上,eval(/any regex/+ '')
将获得相同的正则表达式。
var regex = /video\/(.*)@/;
var text = `el.href.match(${regex})[1]`;
// Or:
var text = `el.href.match(` + /video\/(.*)@/ + ')[1]';
/video\/(.*)@/igm + '' === '/video\\/(.*)@/gim';
new RegExp('video\\/(.*)@', 'gmi') + '' === '/video\\/(.*)@/gim';
关于javascript - 语法错误 : expected expression, 得到 '.',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40191536/