SyntaxError:期望的表达式,得到了“." [英] SyntaxError: expected expression, got '.'

查看:197
本文介绍了SyntaxError:期望的表达式,得到了“."的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道这个JavaScript错误的来源吗?

Does someone know where this JavaScript error comes from?

SyntaxError: expected expression, got '.'

当使用带有正斜杠(转义)(如el.href.match(/video\/(.*)@/)[1];)作为传递给诸如createTextNode,textContent或innerHTML之类的函数的字符串时,会出现此错误.

I get this error when using a regular expression with a slash (escaped) like el.href.match(/video\/(.*)@/)[1]; as a string passed to a function like createTextNode, textContent or innerHTML.

此正则表达式在不存储为文本时有效. 当文本有效时,不带斜杠的正则表达式,您可以看到我的代码示例:

This regex works when not stored as text. A regex without slash as text works, you can see my code example:

HTML:

<a style="display: none; width: 840px; height: 472px;" href="http://videos.francetv.fr/video/147338657@Info-web" id="catchup" class="video"></a>

JavaScript:

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);

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

Working and failing tests can be found here:

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

您可以在GitHub Pages上对其进行实时测试(在我的情况下,JSFiddle无效):

You can test it live on GitHub Pages (JSFiddle did not work in my case):

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

推荐答案

您正在转义正斜杠,而不是笨拙的斜杠.

You are escaping the forward slash instead of having a baskward slash.

`el.href.match(/video\/(.*)@/)[1]` === 'el.href.match(/video/(.*)@/)[1]'
// '\/' == '/', not '\\/'

您还需要转义反斜杠:

`el.href.match(/video\\/(.*)@/)[1]`

您还可以通过正则表达式的字符串表示形式,以获取其源代码表示形式.基本上,eval(/any regex/ + '')将获得相同的正则表达式.

You can also take advantage of the template string with the string representation of a regex to get it's source code representation. Basically, eval(/any regex/ + '') will get the same 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';

这篇关于SyntaxError:期望的表达式,得到了“."的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆