最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript error: Invalid regular expression flags - Stack Overflow

programmeradmin4浏览0评论

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

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

Share Improve this question asked Aug 5, 2017 at 2:55 HazardHazard 1531 gold badge2 silver badges10 bronze badges 1
  • Maybe the browser thinks it's an expression? – Hazard Commented Aug 5, 2017 at 2:56
Add a comment  | 

2 Answers 2

Reset to default 13

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"

Strings need to be in quotes:

ctx.drawImage("/Users/aUser/Desktop/NightSquare.png", 200, 200);
发布评论

评论列表(0)

  1. 暂无评论