javascript - 语法错误 : expected expression, 得到 '.'

标签 javascript regex syntax-error textnode createtextnode

有人知道这个 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);

可以在这里找到工作和失败的测试:

https://github.com/baptx/baptx.github.io/blob/65f11b77df5a7464365374b3505921a4ef9b1272/get_m3u8_debug/get_m3u8_debug.htm

您可以在 GitHub Pages 上对其进行实时测试(JSFiddle 在我的案例中不起作用):

https://baptx.github.io/get_m3u8_debug/get_m3u8_debug.htm

最佳答案

您正在转义正斜杠而不是反斜杠。

`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/

相关文章:

javascript - 查看 Canvas 元素源代码

java - 用于替换查询参数中的值的正则表达式

javascript - asp.net Intranet 站点部署后取消缓存用户浏览器内容?

javascript - Chrome 调试器中的 ES6 (React) 不起作用

python 正则表达式匹配不起作用

javascript - 从 TitleCase、camelCase 获取最后一个词的正则表达式

Linux "missing"错误

oracle - 如何将记录类型值传递给函数参数

python - 安装 PIL 时出现语法错误

javascript - 我怎样才能从php中获取数据到js