简体   繁体   English

String.endsWith(/ [字符串] / [1-999] /)

[英]String.endsWith(/[string]/[1-999]/)

I'm trying to parse the end of a url and redirect depending on it's ending. 我正在尝试解析url的结尾并根据其结尾进行重定向。

For example, if I'm going to www.something.com/foo/1/ I want to redirect to www.something.com/foo/1/bar . 例如,如果我要去www.something.com/foo/1/我想重定向到www.something.com/foo/1/bar The 1 in this case can be any positive integer. 在这种情况下,1可以是任何正整数。

What I've been trying with but can't get to work is: 我一直在尝试但无法正常工作的是:

if (window.location.href.endsWith('/foo/\\d/')) { fetch stuff and redirect } else { do something else }

Which doesn't work, I'm guessing endsWith can't parse regex. 这是行不通的,我猜endsWith不能解析正则表达式。

Thanks in advance, 提前致谢,

Peter 彼得

In your code endsWith('/foo/\\d/') check the string is ending with that particular string argument and won't work as a regex. 在您的代码endsWith('/foo/\\d/')检查字符串是否以该特定字符串参数结尾,并且不能用作正则表达式。

For checking using regex use RegExp#test method with regex /foo\\/\\d{1,3}\\/$/ . 要使用正则表达式进行检查,请对Regex /foo\\/\\d{1,3}\\/$/使用RegExp#test方法。

if(/foo\/\d{1,3}\/$/.test(window.location.href)) 

You can regex match for the end of string instead, 您可以将正则表达式匹配为字符串的结尾,

/.*foo\d/$/

My regex might be wrong, but you can use the $ to denote end of string and just do a regular regex.test 我的正则表达式可能是错误的,但是您可以使用$表示字符串的结尾,而只需执行常规的regex.test

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

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