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

Ngắt dòng (line break) trong giá trị mảng JavaScript


Để thêm ngắt dòng (<br>) trong giá trị mảng cho mỗi ký tự ~, tách mảng bằng split rồi join với <br>.

Ví dụ

Input: "This is demo text 1!~This is demo text 2!~~This is demo text 3!"

Sau split bởi ~ và join với <br>:

This is demo text 1!
This is demo text 2!

This is demo text 3!

Code hoàn chỉnh

<!DOCTYPE html>
<html>
  <body>
    <h2>Thêm ngắt dòng</h2>
    <script>
      var myArray = 'This is demo text 1!~This is demo text 2!~~This is demo text 3!~This is demo text 4!~~This is demo text 5!';
      document.write("Original Array: " + myArray);
      var brk = myArray.split('~');
      var res = brk.join(" <br> ");
      document.write("<br><br>" + res);
    </script>
    <p>Mỗi ~ thêm một ngắt dòng.</p>
  </body>
</html>

Giải thích

  1. split('~'): Tách string thành mảng tại mỗi ~. ~~ tạo ra empty string element (dòng trống).
  2. join(" <br> "): Nối mảng thành string, chèn <br> giữa các phần tử.
  3. Kết quả render HTML sẽ hiển thị xuống dòng.

Cách hiện đại (ES6+)

const text = `Line 1~Line 2~~Line 3`;
const html = text
  .split('~')
  .map(s => s.trim()) // optional: trim whitespace
  .join('
'); // Hoặc dùng replaceAll (ES2021) const html2 = text.replaceAll('~', '
');

Lưu ý bảo mật (XSS)

Nếu input từ user, phải escape HTML trước khi join/render:

function escapeHtml(str) {
  return str.replace(/[&<>"']/g, 
    c => ({'&': '&', '<': '<', '>': '>', '"': '"', "'": '''}[c]));
}

const safeHtml = userInput.split('~').map(escapeHtml).join('
');