[英]Regex to match the URL last part with JavaScript
I have some URLs and I like to catch the final part of the url.我有一些 URL,我想抓住 url 的最后一部分。
My URLs are in the form of我的网址采用以下形式
http://www.my-site.dch/wp-content/uploads/2012/02/Tulips.jpg
http://www.my-site.dch/wp-content/uploads/2012/02/Tulips-150x200.jpg
http://www.my-site.dch/wp-content/uploads/2012/02/Tulips-500x350.jpg
and what I like to catch is the /Tulips.......jpg而我喜欢捕捉的是/Tulips.......jpg
I have try that but with no luck我试过了,但没有运气
\/.*(-\d+x\d+)\.(jp(e)?g|png|gif)
Any better idea?有更好的主意吗?
Take a look at the lastIndexOf
method: 看一下
lastIndexOf
方法:
var index = url.lastIndexOf("/");
var fileName = url.substr(index)
以下正则表达式将起作用:
/[^\/]+$/
Use this Regex:- 使用此正则表达式: -
^((http[s]?|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$
Get file name using $6
使用
$6
获取文件名
In case you came here looking to find the last part of the url even if the url ends with /
There's a solution which is simpler than any regex solution.如果您来这里寻找 url 的最后一部分,即使 url 以
/
结尾,也有一个比任何正则表达式解决方案都简单的解决方案。 Even though the question is regarding regex, I will add it because it does add some value here.即使问题是关于正则表达式的,我也会添加它,因为它确实在这里增加了一些价值。
If the url was this http://www.my-site.dch/wp-content/uploads/2012/02/Tulips.jpg
如果 url 是这个
http://www.my-site.dch/wp-content/uploads/2012/02/Tulips.jpg
const url = 'http://www.my-site.dch/wp-content/uploads/2012/02/Tulips.jpg'
const lastpart = url.split('/').filter(e => e).pop()
In this case, the last part would return the last part even if it ends with /
So, if you had a url like this在这种情况下,最后一部分将返回最后一部分,即使它以
/
结尾所以,如果你有这样的 url
/services/mosquito-control/
and you wanted to catch mosquito-control
, you would be do it with this.并且你想
mosquito-control
,你会用这个来做。
.*/(.*)
use this pattern and get the group 1.it will work I guess. .*/(.*)
/(。* .*/(.*)
使用这种模式并获得组1.我会猜测。
.*
is a greedy regex so it will match until the last slash. .*
是一个贪婪的正则表达式,所以它将匹配到最后一个斜杠。 After that in group 1 will be the last characters (what you need) 之后在第1组中将是最后一个角色(你需要什么)
If you are sure that all the images are jpg: 如果您确定所有图像都是jpg:
/.\/\S+\.jpg/
Otherwise, more generale: 否则,更多属:
/.\/\S+\.\w{2,3}/
That is: 那是:
. any char
\/ the slash before the file name
\S+ any non blank char to match the file name (at least one)
\. the file extension separator
jpg or \w{3,4} the file extension
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.