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

Tách chuỗi (Split String) tại ký tự cụ thể trong JavaScript


Để tách chuỗi tại mỗi ký tự ~, dùng split('~') thành mảng, sau đó join('<br>') để chèn ngắt dòng.

Ví dụ

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

Sau split ~ và join <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>

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

const text = 'Line 1~Line 2~~Line 3';

// split + join
const html = text.split('~').join('
'); // replaceAll (ES2021) - đơn giản hơn const html2 = text.replaceAll('~', '
'); // Regex replace (hỗ trợ multiple delimiters) const html3 = text.replace(/~/g, '
');

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

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

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

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

Split với Regex (Nâng cao)

// Tách bằng nhiều delimiter
'one, two;three four'.split(/[,;\s]+/); // ['one', 'two', 'three', 'four']

// Giữ delimiter trong kết quả
'a,b,c'.split(/(,)/); // ['a', ',', 'b', ',', 'c']

// Giới hạn số phần tử
'a,b,c,d'.split(',', 2); // ['a', 'b']