用正则表达式验证 slug,允许斜杠。

huangapple go评论78阅读模式
英文:

Validate slug with Regexp with slash allowed

问题

我使用正则表达式来验证一个 slug。

const rule = new RegExp('^[A-Za-z0-9]+(-[A-Za-z0-9]+)*$')

尽管它工作得很好,但我想要接受 /

示例:my-parent-page/my-child-page

使用我的原始正则表达式,此 slug 被视为无效,但实际上它应该是正确的。

谢谢

英文:

I use regexp to validate a slug.

const rule = new RegExp('^[A-Za-z0-9]+(-[A-Za-z0-9]+)*$')

It works well though, I would like to / have them accepted

Example: my-parent-page/my-child-page

With my original Regex, this slug is invalidated while it should be correct

Thank you

答案1

得分: 2

Add a slash to the delimiting expression [-/], so the alphanumeric part can be joined by either...

const re = new RegExp('^[A-Za-z0-9]+([-/][A-Za-z0-9]+)*$');

const egs = [
  'justSlash/justSlash',
  'just-dash',
  'dash-and-slash/dash-and-slash',
  '&crap'
];

egs.forEach(eg => console.log(re.test(eg) ? "match" : "no match"))
英文:

Add a slash to the delimiting expression [-/], so the alphanumeric part can be joined by either...

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const re = new RegExp(&#39;^[A-Za-z0-9]+([-/][A-Za-z0-9]+)*$&#39;);

const egs = [
  &#39;justSlash/justSlash&#39;,
  &#39;just-dash&#39;,
  &#39;dash-and-slash/dash-and-slash&#39;,
  &#39;&amp;crap&#39;
];

egs.forEach(eg =&gt; console.log(re.test(eg) ? &quot;match&quot; : &quot;no match&quot;) )

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月8日 21:13:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76432229.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定