亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將輸入的字符串識別為 URL - JavaScript

如何將輸入的字符串識別為 URL - JavaScript

繁花如伊 2023-07-14 09:41:00
我有一個輸入字段,可以在其中輸入任何文本,包括其中的 URL。如果輸入的是長 URL,我想縮短它(我將通過 API 處理這個問題)。HTML:<input type="text" onKeyDown={this.onKeyDown(event)}/>JavaScript:function onKeyDown(event) { var stringWithURL = "Hello, World! https://www.google.com. I'm delighted to be a part of "https://amazon.com". Come again";  if (event.keyCode === 32 || event.keyCode === 13) { // Space bar and enter keys      let url;      try {        url = new URL(stringWithURL); // This text includes simple text as well as URL as a string        if(url.protocol === "http:" || url.protocol === "https:") {          return this.convertLongURLtoShort(stringWithURL); // Call API function        }      } catch (e) {        return false;      }    }}但是,上述函數無法識別簡單文本與 URL,因為輸入文本將整個內容視為單個字符串。因此它總是進入失敗函數,我永遠無法將 URL 轉換為短 URL。當我們在輸入字段中輸入內容時(可能是在按空格鍵或 Enter 鍵后),是否有辦法識別文本與 URL,并在用戶輸入的單詞是 URL 時調用 API?
查看完整描述

2 回答

?
ibeautiful

TA貢獻1993條經驗 獲得超6個贊

因為:

如果給定的基本 URL 或結果 URL 不是有效的 URL,則會引發 JavaScript TypeError 異常。?

function isURL(me){

? try {?

? ? new URL(me);

? ? console.log(me + " is a valid URL!");

? ? return true

? }?

? catch (e){

? ? console.log(e.message);

? ? return false

? }

}


console.log(isURL("/home/dev/infos"))

console.log(isURL("https://website.com"))

console.log(isURL(88))

console.log(isURL("Hello_World!"))

<input onKeyDown="isURL(this.value)">


查看完整回答
反對 回復 2023-07-14
?
慕哥6287543

TA貢獻1831條經驗 獲得超10個贊

在這種情況下,我建議使用正則表達式根據輸入字符串拆分 URL。

該模式可以在這里找到:

https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)

另外,在您的示例字符串中,由于某些 URL 以點 (.) 字符結尾,因此您需要刪除最后一個字符。

function onKeyDown(event) {

? var stringWithURL = "Hello, World! https://www.google.com. I'm delighted to be a part of \"https://amazon.com\". Come again";

? if (event.keyCode === 32 || event.keyCode === 13) { // Space bar and enter keys

? ? ? let pattern = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g

? ? ? let urls = stringWithURL.match(pattern);


? ? ? for (let url of urls) {

? ? ? ? if (url.endsWith('.')) {

? ? ? ? ? // Removing the last character if the URL ends with a dot

? ? ? ? ? url = url.slice(0, url.length - 1);

? ? ? ? }


? ? ? ? // Parsing to URL

? ? ? ? url = new URL(url);


? ? ? ? if(url.protocol === "http:" || url.protocol === "https:") {

? ? ? ? ? console.log(url);

? ? ? ? }

? ? ? }

? ? }

}

<input type="text" onKeyDown="onKeyDown(event)"/>


查看完整回答
反對 回復 2023-07-14
  • 2 回答
  • 0 關注
  • 169 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號