---
# System prepended metadata

title: 判斷字串是否為連結並轉成a tag
tags: [Javascript]

---

---
tags: Javascript,
disqus: hackmd
---

###### tags: `regex` `Regular Expression`

# 判斷字串是否為連結並轉成a tag

參考資料
[Check if a JavaScript string is a URL](https://stackoverflow.com/questions/5717093/check-if-a-javascript-string-is-a-url)

---

在做留言板的時候，想著其他的留言板是如何做到使用者貼入連結留言後，可以把字串轉變成a連結的做法。

```javascript=
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);
}
```

或者是參考[同一篇]((https://stackoverflow.com/questions/5717093/check-if-a-javascript-string-is-a-url))裡的這個方法

```javascript=
function isValidUrl(string) {
  try {
    new URL(string);
  } catch (_) {
    return false;  
  }

  return true;
}
```

也有人提到

```javascript=
var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";

parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port;     // => "3000"
parser.pathname; // => "/pathname/"
parser.search;   // => "?search=test"
parser.hash;     // => "#hash"
parser.host;     // => "example.com:3000"

function isValidURL(str) {
   var a  = document.createElement('a');
   a.href = str;
   return (a.host && a.host != window.location.host);
}
```