简体   繁体   English

Javascript-从网址中的文件名中删除后缀

[英]Javascript - Remove postfix from filename in url

I have a urls like this: 我有这样的网址:

http://localhost/static/1941ce/917985481634941-350x_.png
http://localhost/static/1941ce/917985481634941-350x120.png

and I need to extract the original file name like this: 我需要像这样提取原始文件名:

http://localhost/static/1941ce/917985481634941.png

What is a good way of doing this in Javascript? 用Javascript做这件事的好方法是什么? Cheers! 干杯!

You should use regex for this: 您应该为此使用正则表达式:

 var str1 = 'http://localhost/static/1941ce/917985481634941-350x_.png'; var str2 = 'http://localhost/static/1941ce/917985481634941-350x120.png'; var postfixRe = /-[0-9x_]*\\./i; console.log(str1.replace(postfixRe, '.')); console.log(str2.replace(postfixRe, '.')); 

If you are not sure that there will be only one occurence of '-': 如果您不确定是否只会出现“-”:

 var str1 = 'http://localhost/static/1941ce/917985481634941-350x_.png'; var str2 = 'http://localhost/static/1941ce/917985481634941-350x120.png'; var postfixRe = /\\/(\\d+)-[0-9x_]*\\./i; console.log(str1.replace(postfixRe, '/$1.')); console.log(str2.replace(postfixRe, '/$1.')); 

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

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