Serials Javascript Style Guide – Strings

  Javascript    —  2019, May 27    

Strings

6.1 Quotes

Sử dụng dấu nháy đơn '' đối với strings. eslint: quotes

// bad
const name = "Capt. Janeway";

// bad - template literals should contain interpolation or newlines
const name = `Capt. Janeway`;

// good
const name = 'Capt. Janeway';

6.2 Line length

Không nên nối chuỗi nếu chuỗi quá dài.

Tại sao ư? Thật không dễ làm việc với các chuỗi đã chia nhỏ và điều này làm cho việc tìm kiếm kém hiệu quả hơn.

// bad
const errorMessage = 'This is a super long error that was thrown because \
of Batman. When you stop to think about how Batman had anything to do \
with this, you would get nowhere \
fast.';

// bad
const errorMessage = 'This is a super long error that was thrown because ' +
  'of Batman. When you stop to think about how Batman had anything to do ' +
  'with this, you would get nowhere fast.';

// good
const errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';

6.3 Template literals

Hãy sử dụng template strings thay vì việc phải nối chuỗi. eslint: prefer-template template-curly-spacing

Tại sao ư? Vì nó giúp code dễ đọc và không lo ngại việc xuống dòng nếu như cần xuống dòng.

// bad
function sayHi(name) {
  return 'How are you, ' + name + '?';
}

// bad
function sayHi(name) {
  return ['How are you, ', name, '?'].join();
}

// bad
function sayHi(name) {
  return `How are you, ${ name }?`;
}

// good
function sayHi(name) {
  return `How are you, ${name}?`;
}

6.4 Eval

Đừng bao giờ sử dụng eval() trong 1 chuỗi vì nó tạo ra quá nhiều lỗ hổng. eslint: no-eval

6.5 Escaping

Không cần thiết escape các ký tự trong chuỗi. eslint: no-useless-escape

Tại sao ư? Vì dấu gạch chéo ngược gây khó đọc và chỉ nên sử dụng khi cần thiết.

// bad
const foo = '\'this\' \i\s \"quoted\"';

// good
const foo = '\'this\' is "quoted"';
const foo = `my name is '${name}'`;

Tổng hợp Serial Javascript Style Guide