JavaScript正規表示式用於URL檢測和拆分
P粉043432210
P粉043432210 2023-09-21 18:00:47
0
1
582

我有以下網址:

https://comanage.example.edu/sp
https://wiki.cs.example.org/sp
https://intranet.math.example.edu/sp
https://myapp.example.com/sp

對於這些URL,我需要定義一個函數來偵測它們是否為URL,並從中替換掉https://和sp路徑。基本上,我只需要主機名稱。例如,如下所示:

https://comanage.example.edu/sp      ->comanage.example.edu
https://wiki.cs.example.org/sp       ->wiki.cs.example.org
https://intranet.math.example.edu/sp ->intranet.math.example.edu
https://myapp.example.com/sp         ->myapp.example.com

對於非URL,該函數應該檢測並不進行替換。如下圖所示:

nonurl.example.com -> ***no replacement***

請問有人能為我提供上述問題的解決方案嗎?我對正規表示式的使用知識不多。

P粉043432210
P粉043432210

全部回覆(1)
P粉680087550

模式 ^https?:\/\/ 在這裡應該很容易使用。我們可以用它來替換任何字串開頭的 http://https:// 為空字串

在模式中,^ 符號表示字串的開頭。這意味著如果 http:// 在字串中間出現,它將不會匹配,因為它必須在開頭

? 將前一個字元標記為可選。在模式中,s 是可選的,以便找到 httphttps

\/ 是必要的,因為斜線必須進行轉義

const urls = [
  'https://comanage.example.edu/sp',
  'https://wiki.cs.example.org/sp',
  'https://intranet.math.example.edu/sp',
  'https://myapp.example.com/sp',
  'nonurl.example.com',
];

const pattern = /^https?:\/\//i;

urls.forEach(u => {
  console.log(u, '-->', u.replace(pattern, ''));
});
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!