3 回答

TA貢獻1865條經驗 獲得超7個贊
您可以使用一些正則表達式來實現這一點。
function validURL(str) {
var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
'(\\#[-a-z\\d_]*)?$','i'); // fragment locator
return !!pattern.test(str);
}

TA貢獻1906條經驗 獲得超10個贊
你很接近,但你需要設置img.src = url
開始嘗試加載:)另外,刪除檢查if (callback === true)
因為這沒有意義;callback 是一個函數,而不是一個布爾值。布爾值作為 onload / onerror 處理程序中的參數傳遞給函數。

TA貢獻1719條經驗 獲得超6個贊
通過獲取圖像本身來檢查怎么樣,有效的 url 實際上不是真實的圖像,你可以這樣做的方式,也許通過這樣做
const contentTypePart = "image";
const isImage = (url) => new Promise((resolve, reject) => {
// check that is a valid url
// then if valid url
fetch(url).then((response) => {
if (response.ok) {
const currentContentType = response.headers.get('Content-Type');
// check if the content type is actually an image extension
if (currentContentType.indexOf(contentTypePart) > -1) {
return resolve(url);
}
}
reject(false);
}).catch(reject)
})
或者如果您更喜歡使用 Image 構造函數
const contentTypePart = "image";
const isImage = (url) => new Promise((resolve, reject) => {
// check that is a valid url
// then if valid url
const image = new Image();
image.src = url;
image.onload = resolve;
image.onerror = reject;
});
最后的使用方法是
isImage('https://www.google.com/').then(console.log.bind(null, 'is a valid image')).catch(console.error.bind(null, 'is not a valid image'))
上面的代碼會拋出一個,console.error因為 url 是一個網站而不是一個圖像。
通過這樣做,您可以檢查該 url 實際上是一個真實有效的圖像。
添加回答
舉報