英文:
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('^[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") )
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论