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

Sắp xếp chuỗi có dấu (Accented Characters) trong JavaScript


Array.prototype.sort() mặc định so sánh Unicode code point -> sai với chữ có dấu. Dùng localeCompare() với locale 'vi' (hoặc 'utf-8') để sắp xếp đúng quy tắc ngôn ngữ.

Ví dụ

Sắp xếp mảng tiếng Việt: ['quê', 'cómo', 'đónde', 'quién', 'cuánto', 'cuántos'] (ví dụ gốc dùng tiếng Tây Ban Nha, áp dụng tương tự cho tiếng Việt):

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Sort accented strings</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result, .sample { font-size: 18px; font-weight: 500; color: blueviolet; }
    .sample { color: red; }
  </style>
</head>
<body>
  <h1>Sắp xếp chuỗi có dấu (Accented Characters)</h1>
  <div class="sample">[quê, cómo, dónde, quién, cuánto, cuántos]</div><br>
  <div class="result"></div><br>
  <button class="Btn">SẮP XẾP</button>
  <h3>Nhấn nút để sắp xếp mảng theo localeCompare</h3>
  <script>
    const resEle = document.querySelector('.result');
    const btn = document.querySelector('.Btn');
    const arr = ['quê', 'cómo', 'đónde', 'quién', 'cuánto', 'cuántos'];
    btn.addEventListener('click', () => {
      const sorted = [...arr].sort((a, b) => a.localeCompare(b, 'vi'));
      resEle.textContent = `[${sorted.join(', ')}]`;
    });
  </script>
</body>
</html>

Kết quả

Sắp xếp đúng thứ tự bảng chữ cái: cuánto, cuántos, cómo, dónde, quién, quê (theo locale 'vi' hoặc mặc định).

Mẹo: arr.sort((a,b) => a.localeCompare(b, 'vi', {sensitivity: 'base'})) bỏ qua dấu/hoa thường nếu cần.