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

Nối 2 chuỗi khi chuỗi đầu đã có khoảng trắng trong JavaScript

Khi nối chuỗi với +, nếu chuỗi đầu đã kết thúc bằng khoảng trắng, không cần thêm " " thủ công.

Chuỗi đầu có space cuối

<script>
  function noiChuoi(str1, str2) {
    return str1 + str2; // Không cần + " "
  }

  document.write(noiChuoi("Tutorix is the best ", "e-learning platform"));
  // "Tutorix is the best e-learning platform"
</script>

Chuỗi đầu KHÔNG có space cuối

<script>
  function noiChuoiCoSpace(str1, str2) {
    return str1 + " " + str2; // Phải thêm space
  }

  document.write(noiChuoiCoSpace("Tutorix is the best", "e-learning platform"));
  // "Tutorix is the best e-learning platform"
</script>

Cách an toàn: Tự động xử lý

function noiAnToan(str1, str2) {
  const s1 = String(str1).trimEnd();
  const s2 = String(str2).trimStart();
  return s1 + (s1 && s2 ? ' ' : '') + s2;
}

// Test
noiAnToan("Hello ", "world");    // "Hello world"
noiAnToan("Hello", " world");    // "Hello world"
noiAnToan("Hello", "world");     // "Hello world"
noiAnToan("Hello ", " world");   // "Hello world" (không double space)

Template Literal (ES6) — Tự nhiên hơn

const greeting = `${str1}${str2}`;           // Không auto space
const greeting2 = `${str1.trimEnd()} ${str2.trimStart()}`; // An toàn

Tóm tắt

Trường hợpCodeKết quả
str1 có space cuốistr1 + str2Đúng (1 space)
str1 không space, str2 có space đầustr1 + str2Đúng (1 space)
Cả hai đều không spacestr1 + " " + str2Đúng
Cả hai đều có spacestr1 + str2Sai (2 space) → dùng trim