简体   繁体   English

需要 JavaScript 中的正则表达式来匹配 '/' 或 '/login'

[英]Need a Regex in JavaScript to match '/' or '/login'

I need a regex to match either '/' or '/login' at the end of my url.我需要一个正则表达式来匹配 url 末尾的“/”或“/login”。 Here is my regex which I am trying.这是我正在尝试的正则表达式。

/\\/(login)?$/.test(window.location.href)

This is what the expected result.这就是预期的结果。

/\/(login)?$/.test('/')             //true
/\/(login)?$/.test('/login')        //true
/\/(login)?$/.test('//')            // false
/\/(login)?$/.test('/login/login')  //false

Basically I want to match exactly one set not multiple.基本上我想完全匹配一组而不是多个。

It would seem that you're testing window.location.href when what you really want is window.location.pathname .这似乎是你正在测试window.location.href当你真正想要的是window.location.pathname You'd then just need anchors at both ends of the RegExp:然后你只需要在 RegExp 的两端都有锚点:

/^\/(login)?$/.test(window.location.pathname)

You could attempt something using window.location.href like this:你可以尝试使用window.location.href像这样:

/^https?:\/\/[^\/]*\/(login)?$/.test(window.location.href)

Problem is it's very fragile, it only needs something like a hash section to break it.问题是它非常脆弱,它只需要像hash部分这样的东西来破坏它。 It's much safer to let the browser parse the URL for you.让浏览器为您解析 URL 安全得多。

The need to check for preceding repetitions usually implies using lookbehind, here a negative one, which are not available in javascript.需要检查前面的重复通常意味着使用lookbehind,这里是否定的,这在javascript中不可用。
The simpler way to go here is to code a bit:更简单的方法是编写一些代码:

var test = [ '/', '/login', '//', '/login/login' ];

var reForFail = /(\/(?:login)?)\1$/;
var reForMatch = /\/(?:login)?$/;

console.log(test.map(e => !reForFail.test(e) && reForMatch.test(e)));

You may also have a look at Steven Levithan's mimic-lookbehind-javascript .你也可以看看 Steven Levithan 的 mimim - lookbehind -javascript

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM