Javascript error: Invalid regular expression flags

16,445

Solution 1

Any thing in between / & / is treated as a regular expression in Javascript. There are 2 ways of creating regular expressions in JavaScript.

var myRegEx = new RegExp("pattern") ;
var myRegEx = /pattern/ ;

So using /Users/aUser/Desktop/NightSquare.png is actually leading to your code being interpreted as some regular expression creation which you do not intend. Just make it a string literal( using "" or '') and it will be fine.

In case aUser is a variable ,use the following string concatenation-

"/Users/"+aUser+"/Desktop/NightSquare.png"

Solution 2

Strings need to be in quotes:

ctx.drawImage("/Users/aUser/Desktop/NightSquare.png", 200, 200);
Share:
16,445
Hazard
Author by

Hazard

Hi! I like to program JS and HTML. I enjoy reading xkcd.

Updated on July 30, 2022

Comments

  • Hazard
    Hazard over 1 year

    So I have an error in my code that's saying Invalid regular expression flags. The line at fault is this one: ctx.drawImage(/Users/aUser/Desktop/NightSquare.png, 200, 200);, but aUser is replaced with my actual name (changed for privacy). I'm running on a mac and I think I know what the problem is (I didn't include MacIntosh HD), but I'm not sure. How do I fix this?
    Additional notes: The /Users/ part of the code is highlighted in red in my text editor (the same color as a string).

    • Hazard
      Hazard over 6 years
      Maybe the browser thinks it's an expression?
  • Dave Smash
    Dave Smash about 3 years
    I did the same thing while passing a path to a function. I've done it a million times correctly, but the IDE didn't flag it as a problem when I forgot the quotes because it thought it was a regex. Thanks for pointing me in the right direction!