【问题标题】:regex works in js but fails in html正则表达式在 js 中有效,但在 html 中失败
【发布时间】:2022-01-08 01:29:54
【问题描述】:

我得到了一个匹配 YouTube URI 的正则表达式

/^(https:\/\/youtu.be\/|https:\/\/www.youtube.com\/watch\?v=|https:\/\/www.youtube-nocookie.com\/embed\/)([a-zA-Z0-9]{6,12})+/

在js中效果很好

/^(https:\/\/youtu.be\/|https:\/\/www.youtube.com\/watch\?v=|https:\/\/www.youtube-nocookie.com\/embed\/)([a-zA-Z0-9]{6,12})+/.test('https://www.youtube.com/watch?v=PZP1wGptlUE&list=RDT4X7Ev7RIZA&index=2')
// true

但是为什么它在 html input[pattern] 中失败了?

请匹配要求的格式

function handle(e) {
  e.preventDefault();
}
<form onsubmit="handle">
  <input placeholder="YouTube URI"
      type="url"
      pattern="^(https:\/\/youtu.be\/|https:\/\/www.youtube.com\/watch\?v=|https:\/\/www.youtube-nocookie.com\/embed\/)([a-zA-Z0-9]{6,12})+" 
      value="https://www.youtube.com/watch?v=PZP1wGptlUE&list=RDT4X7Ev7RIZA&index=2"
      required>
  <button type="submit">submit</button>
</form>

【问题讨论】:

  • 仅供参考,_ 和 - 视频 ID 中可能还允许使用更多字符。

标签: javascript html regex


【解决方案1】:

HTML 输入模式末尾有一个隐含的$,这意味着它希望匹配整个 输入。

你没有考虑&amp;list=RDT4X7Ev7RIZA&amp;index=2,所以它失败了。

您可以添加类似(\&amp;.*)? 的内容来修复它

【讨论】:

  • 一开始是隐含的^
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多