You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JSHint检测JS代码时出现Invalid Regular expression错误求助

Fixing JSHint's "Invalid Regular Expression" Error for Your Pattern Array

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 .jshintrc configuration 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:08:47