baptx baptx - 3 years ago 328
Javascript Question

SyntaxError: expected expression, got '.'

Does someone know where this JavaScript error comes from?

SyntaxError: expected expression, got '.'

I get this error when using a regular expression with a slash (escaped) like
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:

var script = document.createElement("script");
var text = `
(function() {
var id = el.href.match(/video\/(.*)@/)[1];
alert("test 4 - regex with slash as text: " + id);


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

Answer Source

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

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

You need to escape the backward slash as well:


What I would suggest to still use a regex literal would be to use it's .source:

var regex = /video\/(.*)@/
var text = `el.href.match(/${regex.source}/)[1]`
// Or:
var text = `el.href.match(/` + /video\/(.*)@/.source + `/)[1]`
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download