我正在获取一个长url字符串,并解析出文件名以使用fs.writefile((保存。大多数堆栈答案都说使用lastIndexOf('/'(,但当文件名出现在url中后有多个修饰符时,这就不起作用了。我创建了一个函数,递归地删除最后一个"/"之后的最后一个部分,直到找到有效的文件名。我在这里错过了什么?为什么我变得不明确了?
exports.shortFileNameFn = (longUrlPath) => {
if (longUrlPath) {
//remove possible url querystring
if (longUrlPath.lastIndexOf('?')>-1) longUrlPath=longUrlPath.substring(0,longUrlPath.lastIndexOf('?'));
//recursively remove the section after the last '/' until a valid filename occurs
const idx = longUrlPath.lastIndexOf('/');
if (/^(?=[S])[^\ / : * ? " < > | ]+$/.test(longUrlPath.substring(idx + 1))) {
const validFileName = longUrlPath.substring(idx + 1);
console.log(validFileName); //Returns SB_20Detail.jpg
return validFileName;
}
//if name not yet valid, remove last section and call function again
longUrlPath = longUrlPath.substring(0, idx);
this.shortFileNameFn(longUrlPath);
}
};
//Calling code in app.js
const { shortFileNameFn } = require('./toStack');
const longProductImageUrl = 'https://img1.wsimg.com/isteam/ip/7ed83e96-6fb7-4d7c-bfe9-1a34fcbed15e/SB_20Detail.jpg/:/cr=t:31.25_25,l:0_25,w:100_25,h:37.5_25/rs=w:388,h:194,cg:true';
const shortProductImageUrl = shortFileNameFn(longProductImageUrl);
console.log('Short File Name:', shortProductImageUrl); //Returns undefined
您递归调用shortFileNameFn
,但不返回结果。你可以用以下方法解决它:
exports.shortFileNameFn = (longUrlPath) => {
if (longUrlPath) {
//remove possible url querystring
if (longUrlPath.lastIndexOf('?')>-1) longUrlPath=longUrlPath.substring(0,longUrlPath.lastIndexOf('?'));
//recursively remove the section after the last '/' until a valid filename occurs
const idx = longUrlPath.lastIndexOf('/');
if (/^(?=[S])[^\ / : * ? " < > | ]+$/.test(longUrlPath.substring(idx + 1))) {
const validFileName = longUrlPath.substring(idx + 1);
console.log(validFileName); //Returns SB_20Detail.jpg
return validFileName;
}
//if name not yet valid, remove last section and call function again
longUrlPath = longUrlPath.substring(0, idx);
return this.shortFileNameFn(longUrlPath);
}
};
要查看递归的发生,请尝试在函数shortFileNameFn
的开头添加一个console.log
,您应该会看到它多次出现。