使用JSHint检测JS代码时出现Invalid Regular expression错误求助
Hey there! Let's break down why JSHint is complaining about your regexes even though they work perfectly in tools like Regex101. The issue comes down to syntax support gaps and unnecessary code wrapping that's tripping up the linter.
Why the Error Happens
1. Named Capture Groups Are ES2018+ Syntax
Your regexes use named capture groups like (?<tag>) and (?<src>)—this is a feature added in ES2018. By default, JSHint doesn't enable support for this newer syntax, so it flags these patterns as invalid. Regex101, on the other hand, typically enables modern regex features out of the box, which is why your tests pass there.
2. Redundant new RegExp() Wrapper
You're wrapping regex literals (like /<...>/) with new RegExp(), which is completely unnecessary. While this alone might not trigger the error, it can confuse JSHint's parser and adds unnecessary overhead to your code.
Solutions to Try
Option 1: Enable ES2018 Support in JSHint
Tell JSHint to recognize ES2018 syntax by either:
- Adding a comment at the top of your JavaScript file:
/* jshint esversion: 8 */ - Or creating a
.jshintrcconfiguration file in your project root with:{ "esversion": 8 }
Option 2: Replace Named Capture Groups with Numbered Ones (For Older Env Compatibility)
If you need your code to work in environments that don't support ES2018, swap named groups for traditional numbered capture groups. For example, change:
new RegExp(/<(?<tag>iframe)[^>]*src=("|')(?<src>[^'" ]*)\2[^>]*>[\s\S]*?<\/\1>/)
to:
/<(iframe)[^>]*src=("|')([^'" ]*)\2[^>]*>[\s\S]*?<\/\1>/
You'll then reference groups by their position (\1, \3, etc.) instead of their name.
Option 3: Remove the Unnecessary new RegExp() Calls
Since you're using regex literals directly, you don't need to wrap them in new RegExp(). Clean up your array like this:
var regexArray = [ /<(?<tag>iframe)[^>]*src=("|')(?<src>[^'" ]*)\2[^>]*>[\s\S]*?<\/\1>/, /<(?<tag>(?:div|span))(?=[^>]*(?:class)=("|')[^'"]*embed[^'"]*\2)(?=[^>]*(?:data-)?(?:src|source|url)=("|')(?<src>[^'" ]*)\3)[^>]*>[\s\S]*?<\/\1>/, /<(?<tag>div)[^>]*id="fb-root"(?<src>[^'" ]*)\2[^>]*>[\s\S]*?<\/\1>/, /<(?<tag>div)[^>]*class="fb-post"(?<class>[^'" ]*)\2[^>]*>[\s\S]*?<\/\1><\/\1>/, /<(?<tag>script)>[\s\S]*?<\/\1>/, /<(?<tag>script)[^>]*src=("|')(?<src>[^'" ]*)\2[^>]*>[\s\S]*?<\/\1>/, /<(?<tag>div)[^>]*class=("|')(?<class>[pb_feed]*)\2[^>]*>[\s\S]*?<\/\1>/ ];
After applying any of these fixes, JSHint should stop throwing the "Invalid Regular Expression" error, and your regexes will keep working as expected.
内容的提问来源于stack exchange,提问作者Juan Jose Polanco Arias

