Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách tạo link (liên kết) từ văn bản bằng JavaScript?

Sử dụng phương thức String.prototype.link() để tạo thẻ <a> HTML từ chuỗi. Lưu ý: Phương thức này đã deprecated (ngừng chuẩn bị), không khuyến khích dùng trong code mới.

Cú pháp (Deprecated)

string.link(url)
  • url: Địa chỉ liên kết (HREF).
  • Trả về chuỗi HTML: <a href="url">string</a>.

Ví dụ (chỉ để hiểu)

<!DOCTYPE html>
<html>
<body>
    <script>
        var str = "Tutorialspoint";
        var url = "https://www.tutorialspoint.com";
        document.write(str.link(url));
        // Kết quả: Tutorialspoint
    </script>
</body>
</html>

Cách hiện đại (Khuyến nghị):

// 1. Tạo element DOM
const a = document.createElement('a');
a.href = 'https://example.com';
a.textContent = 'Liên kết';
document.body.appendChild(a);

// 2. Template literal (chèn HTML)
const linkHTML = `${text}`;
container.innerHTML = linkHTML;

// 3. Gán trực tiếp innerHTML (cẩn thận XSS)
element.innerHTML = `${escapeHtml(text)}`;

Các phương thức String deprecated tương tự:

  • anchor() → <a name="...">
  • big() → <big>
  • small() → <small>
  • bold() → <b>
  • italics() → <i>
  • strike() → <strike>
  • sub() / sup() → <sub> / <sup>
  • fontcolor() / fontsize() → <font>
  • blink() → <blink> (non-standard)

Tất cả đều deprecated. Hãy dùng CSS (font-weight, font-style, text-decoration, font-size, color) và DOM API thay thế.