Cách lấy chữ cái đầu tiên của một từ trong JavaScript

Trong quá trình phát triển website, lập trình viên cần lấy các chuỗi ký tự. Đôi khi, cần phải truy cập ký tự đầu tiên hoặc ký tự cuối cùng hoặc chuỗi con của chuỗi. Ở đây, ký tự đầu tiên của chuỗi là bắt buộc. Để làm như vậy, các phương thức được xác định trước của JavaScript được sử dụng, bao gồm Ký hiệu ngoặc ([ ]), phương thức charAt() hoặc phương thức chuỗi con()

Bài viết này sẽ trình bày các phương pháp lấy chữ cái đầu tiên của chuỗi trong JavaScript

Làm cách nào để lấy ký tự đầu tiên từ một chuỗi trong JavaScript?

Để lấy ký tự đầu tiên của chuỗi, hãy sử dụng các phương thức sau

Hãy xem các phương pháp trên hoạt động như thế nào

Phương pháp 1. Nhận ký tự đầu tiên từ một chuỗi bằng cách sử dụng ký hiệu ngoặc ([ ])

Trong JavaScript, ký hiệu ngoặc ([ ]) là cách tiếp cận cơ bản để lấy ký tự đầu tiên từ một chuỗi. Để làm như vậy, hãy vượt qua chỉ số “0”

cú pháp

Sử dụng cú pháp đã cho để lấy ký tự đầu tiên từ một chuỗi bằng cách sử dụng ký hiệu dấu ngoặc

chuỗi [0]

 
Ở đây, “0” là chỉ số của chuỗi để lấy chữ cái đầu tiên của chuỗi.

Thí dụ

Đầu tiên, tạo một chuỗi và lưu trữ nó trong một biến “chuỗi”

let string = "Chào mừng bạn đến với LinuxHint" ;

 
Nhận ký tự đầu tiên của chuỗi bằng cách sử dụng ký hiệu ngoặc ([ ]) bằng cách chuyển chỉ mục của ký tự đầu tiên là “0” và lưu ký tự đó vào biến “firstChar .

let firstChar = string [0];

 
In chữ cái đầu tiên của chuỗi trên bảng điều khiển bằng cách sử dụng “bảng điều khiển. phương thức log()”.

bảng điều khiển. log ("Ký tự đầu tiên của chuỗi là " + "'" + firstChar + "'");

 
Đầu ra hiển thị “W”, là ký tự đầu tiên của chuỗi.

Cách lấy chữ cái đầu tiên của một từ trong JavaScript

Hãy xem phương thức thứ hai để lấy ký tự đầu tiên của chuỗi

Phương pháp 2. Lấy ký tự đầu tiên từ một chuỗi bằng phương thức charAt()

Để lấy ký tự đầu tiên của chuỗi, hãy sử dụng phương thức “charAt()”. Nó cung cấp ký tự dưới dạng đầu ra trong một chuỗi ở một vị trí cụ thể được gọi là chỉ mục. Đối với ký tự đầu tiên, hãy chuyển chỉ số “0” làm tham số trong phương thức charAt()

cú pháp

Thực hiện theo cú pháp đã cho cho phương thức charAt()

chuỗi. charAt ( chỉ mục )

 
Tại đây, hãy chuyển chỉ số “0” cho phần tử đầu tiên của chuỗi.

Thí dụ

Gọi phương thức charAt() bằng cách chuyển chỉ mục đầu tiên của chuỗi với chuỗi đã tạo và lưu kết quả vào một biến “firstChar”

let firstChar = string. charAt (0) ;

 
Đầu ra tương ứng cho biết “W” là ký tự đầu tiên của chuỗi.

Cách lấy chữ cái đầu tiên của một từ trong JavaScript

Phương pháp 3. Nhận ký tự đầu tiên từ một chuỗi bằng cách sử dụng phương thức substring()

Một phương thức khác để lấy chữ cái đầu tiên của chuỗi là phương thức “substring()”. Nó trích xuất các ký tự từ đầu đến cuối giữa hai chỉ mục và trả về chuỗi con

cú pháp

Cú pháp sau được sử dụng cho phương thức substring()

chuỗi. chuỗi con ( bắt đầu, kết thúc )

 
Ví dụ

Gọi phương thức “substring()” bằng cách chuyển hai chỉ mục, “0”, chỉ mục đầu tiên của chuỗi và “1”, là chỉ mục thứ hai của chuỗi, làm tham số. Nó sẽ phân chia chuỗi giữa các chỉ số này

let firstChar = string. chuỗi con (0 , 1);

 
Kết quả cho biết rằng chữ cái đầu tiên được truy xuất thành công bằng phương thức substring().

Cách lấy chữ cái đầu tiên của một từ trong JavaScript

Tất cả các thông tin liên quan được biên dịch để lấy chữ cái đầu tiên của chuỗi

Sự kết luận

Để lấy ký tự đầu tiên từ một chuỗi, hãy sử dụng các phương thức dựng sẵn của JavaScript, bao gồm Ký hiệu ngoặc ([ ]), phương thức charAt() hoặc phương thức chuỗi con(). Tất cả những cách này lấy thành công chữ cái đầu tiên của chuỗi. Bài viết này đã trình bày các phương pháp lấy ký tự đầu tiên từ một chuỗi trong JavaScript với các ví dụ

Phương thức charAt() của đối tượng String trả về một chuỗi mới bao gồm đơn vị mã UTF-16 duy nhất nằm ở phần bù được chỉ định trong chuỗi

charAt(index)

const anyString = "Brave new world";
console.log(`The character at index 0   is '${anyString.charAt()}'`);
// No index was provided, used 0 as default

console.log(`The character at index 0   is '${anyString.charAt(0)}'`);
console.log(`The character at index 1   is '${anyString.charAt(1)}'`);
console.log(`The character at index 2   is '${anyString.charAt(2)}'`);
console.log(`The character at index 3   is '${anyString.charAt(3)}'`);
console.log(`The character at index 4   is '${anyString.charAt(4)}'`);
console.log(`The character at index 999 is '${anyString.charAt(999)}'`);
0

Một số nguyên giữa

const anyString = "Brave new world";
console.log(`The character at index 0   is '${anyString.charAt()}'`);
// No index was provided, used 0 as default

console.log(`The character at index 0   is '${anyString.charAt(0)}'`);
console.log(`The character at index 1   is '${anyString.charAt(1)}'`);
console.log(`The character at index 2   is '${anyString.charAt(2)}'`);
console.log(`The character at index 3   is '${anyString.charAt(3)}'`);
console.log(`The character at index 4   is '${anyString.charAt(4)}'`);
console.log(`The character at index 999 is '${anyString.charAt(999)}'`);
1 và
const anyString = "Brave new world";
console.log(`The character at index 0   is '${anyString.charAt()}'`);
// No index was provided, used 0 as default

console.log(`The character at index 0   is '${anyString.charAt(0)}'`);
console.log(`The character at index 1   is '${anyString.charAt(1)}'`);
console.log(`The character at index 2   is '${anyString.charAt(2)}'`);
console.log(`The character at index 3   is '${anyString.charAt(3)}'`);
console.log(`The character at index 4   is '${anyString.charAt(4)}'`);
console.log(`The character at index 999 is '${anyString.charAt(999)}'`);
2. Nếu không thể chuyển đổi
const anyString = "Brave new world";
console.log(`The character at index 0   is '${anyString.charAt()}'`);
// No index was provided, used 0 as default

console.log(`The character at index 0   is '${anyString.charAt(0)}'`);
console.log(`The character at index 1   is '${anyString.charAt(1)}'`);
console.log(`The character at index 2   is '${anyString.charAt(2)}'`);
console.log(`The character at index 3   is '${anyString.charAt(3)}'`);
console.log(`The character at index 4   is '${anyString.charAt(4)}'`);
console.log(`The character at index 999 is '${anyString.charAt(999)}'`);
0 thành số nguyên hoặc không cung cấp
const anyString = "Brave new world";
console.log(`The character at index 0   is '${anyString.charAt()}'`);
// No index was provided, used 0 as default

console.log(`The character at index 0   is '${anyString.charAt(0)}'`);
console.log(`The character at index 1   is '${anyString.charAt(1)}'`);
console.log(`The character at index 2   is '${anyString.charAt(2)}'`);
console.log(`The character at index 3   is '${anyString.charAt(3)}'`);
console.log(`The character at index 4   is '${anyString.charAt(4)}'`);
console.log(`The character at index 999 is '${anyString.charAt(999)}'`);
0, giá trị mặc định là
const anyString = "Brave new world";
console.log(`The character at index 0   is '${anyString.charAt()}'`);
// No index was provided, used 0 as default

console.log(`The character at index 0   is '${anyString.charAt(0)}'`);
console.log(`The character at index 1   is '${anyString.charAt(1)}'`);
console.log(`The character at index 2   is '${anyString.charAt(2)}'`);
console.log(`The character at index 3   is '${anyString.charAt(3)}'`);
console.log(`The character at index 4   is '${anyString.charAt(4)}'`);
console.log(`The character at index 999 is '${anyString.charAt(999)}'`);
1, do đó, ký tự đầu tiên của
const anyString = "Brave new world";
console.log(`The character at index 0   is '${anyString.charAt()}'`);
// No index was provided, used 0 as default

console.log(`The character at index 0   is '${anyString.charAt(0)}'`);
console.log(`The character at index 1   is '${anyString.charAt(1)}'`);
console.log(`The character at index 2   is '${anyString.charAt(2)}'`);
console.log(`The character at index 3   is '${anyString.charAt(3)}'`);
console.log(`The character at index 4   is '${anyString.charAt(4)}'`);
console.log(`The character at index 999 is '${anyString.charAt(999)}'`);
3 được trả về

Một chuỗi đại diện cho ký tự (chính xác là một đơn vị mã UTF-16) tại

const anyString = "Brave new world";
console.log(`The character at index 0   is '${anyString.charAt()}'`);
// No index was provided, used 0 as default

console.log(`The character at index 0   is '${anyString.charAt(0)}'`);
console.log(`The character at index 1   is '${anyString.charAt(1)}'`);
console.log(`The character at index 2   is '${anyString.charAt(2)}'`);
console.log(`The character at index 3   is '${anyString.charAt(3)}'`);
console.log(`The character at index 4   is '${anyString.charAt(4)}'`);
console.log(`The character at index 999 is '${anyString.charAt(999)}'`);
0 đã chỉ định. Nếu
const anyString = "Brave new world";
console.log(`The character at index 0   is '${anyString.charAt()}'`);
// No index was provided, used 0 as default

console.log(`The character at index 0   is '${anyString.charAt(0)}'`);
console.log(`The character at index 1   is '${anyString.charAt(1)}'`);
console.log(`The character at index 2   is '${anyString.charAt(2)}'`);
console.log(`The character at index 3   is '${anyString.charAt(3)}'`);
console.log(`The character at index 4   is '${anyString.charAt(4)}'`);
console.log(`The character at index 999 is '${anyString.charAt(999)}'`);
0 nằm ngoài phạm vi, charAt() trả về một chuỗi rỗng

Các ký tự trong một chuỗi được lập chỉ mục từ trái sang phải. Chỉ mục của ký tự đầu tiên là _______ 11 và chỉ mục của ký tự cuối cùng—trong một chuỗi có tên là ________ 18 là ________ 19. Nếu

const anyString = "Brave new world";
console.log(`The character at index 0   is '${anyString.charAt()}'`);
// No index was provided, used 0 as default

console.log(`The character at index 0   is '${anyString.charAt(0)}'`);
console.log(`The character at index 1   is '${anyString.charAt(1)}'`);
console.log(`The character at index 2   is '${anyString.charAt(2)}'`);
console.log(`The character at index 3   is '${anyString.charAt(3)}'`);
console.log(`The character at index 4   is '${anyString.charAt(4)}'`);
console.log(`The character at index 999 is '${anyString.charAt(999)}'`);
0 bạn cung cấp nằm ngoài phạm vi này, JavaScript sẽ trả về một chuỗi trống

Nếu không cung cấp

const anyString = "Brave new world";
console.log(`The character at index 0   is '${anyString.charAt()}'`);
// No index was provided, used 0 as default

console.log(`The character at index 0   is '${anyString.charAt(0)}'`);
console.log(`The character at index 1   is '${anyString.charAt(1)}'`);
console.log(`The character at index 2   is '${anyString.charAt(2)}'`);
console.log(`The character at index 3   is '${anyString.charAt(3)}'`);
console.log(`The character at index 4   is '${anyString.charAt(4)}'`);
console.log(`The character at index 999 is '${anyString.charAt(999)}'`);
0 cho charAt(), thì mặc định là
const anyString = "Brave new world";
console.log(`The character at index 0   is '${anyString.charAt()}'`);
// No index was provided, used 0 as default

console.log(`The character at index 0   is '${anyString.charAt(0)}'`);
console.log(`The character at index 1   is '${anyString.charAt(1)}'`);
console.log(`The character at index 2   is '${anyString.charAt(2)}'`);
console.log(`The character at index 3   is '${anyString.charAt(3)}'`);
console.log(`The character at index 4   is '${anyString.charAt(4)}'`);
console.log(`The character at index 999 is '${anyString.charAt(999)}'`);
1

Ví dụ sau hiển thị các ký tự ở các vị trí khác nhau trong chuỗi "______44"

const anyString = "Brave new world";
console.log(`The character at index 0   is '${anyString.charAt()}'`);
// No index was provided, used 0 as default

console.log(`The character at index 0   is '${anyString.charAt(0)}'`);
console.log(`The character at index 1   is '${anyString.charAt(1)}'`);
console.log(`The character at index 2   is '${anyString.charAt(2)}'`);
console.log(`The character at index 3   is '${anyString.charAt(3)}'`);
console.log(`The character at index 4   is '${anyString.charAt(4)}'`);
console.log(`The character at index 999 is '${anyString.charAt(999)}'`);

Những dòng này hiển thị như sau

The character at index 0   is 'B'

The character at index 0   is 'B'
The character at index 1   is 'r'
The character at index 2   is 'a'
The character at index 3   is 'v'
The character at index 4   is 'e'
The character at index 999 is ''

Điều sau đây cung cấp một phương tiện để đảm bảo rằng việc đi qua một vòng lặp chuỗi luôn cung cấp toàn bộ ký tự, ngay cả khi chuỗi chứa các ký tự không có trong Mặt phẳng đa ngôn ngữ cơ bản

const str = "A\uD87E\uDC04Z"; // We could also use a non-BMP character directly
for (let i = 0; i < str.length; i++) {
  let chr;
  [chr, i] = getWholeCharAndI(str, i);

  // Adapt this line at the top of each loop, passing in the whole string and
  // the current iteration and returning an array with the individual character
  // and 'i' value (only changed if a surrogate pair)

  console.log(chr);
}

function getWholeCharAndI(str, i) {
  const code = str.charCodeAt(i);

  if (Number.isNaN(code)) {
    return ""; // Position not found
  }
  if (code < 0xd800 || code > 0xdfff) {
    return [str.charAt(i), i]; // Normal character, keeping 'i' the same
  }

  // High surrogate (could change last hex to 0xDB7F to treat high private
  // surrogates as single characters)
  if (0xd800 <= code && code <= 0xdbff) {
    if (str.length <= i + 1) {
      throw new Error("High surrogate without following low surrogate");
    }
    const next = str.charCodeAt(i + 1);
    if (next < 0xdc00 || next > 0xdfff) {
      throw new Error("High surrogate without following low surrogate");
    }
    return [str.charAt(i) + str.charAt(i + 1), i + 1];
  }

  // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
  if (i === 0) {
    throw new Error("Low surrogate without preceding high surrogate");
  }

  const prev = str.charCodeAt(i - 1);

  // (could change last hex to 0xDB7F to treat high private surrogates
  // as single characters)
  if (prev < 0xd800 || prev > 0xdbff) {
    throw new Error("Low surrogate without preceding high surrogate");
  }

  // Return the next character instead (and increment)
  return [str.charAt(i + 1), i + 1];
}

Mặc dù ví dụ trước có thể hữu ích hơn cho các chương trình phải hỗ trợ các ký tự không phải BMP (vì nó không yêu cầu người gọi biết bất kỳ ký tự không phải BMP nào có thể xuất hiện ở đâu), trong trường hợp muốn, chọn một ký tự bằng cách

Làm cách nào để tìm ký tự đầu tiên của chuỗi trong JavaScript?

Để lấy ký tự đầu tiên của một chuỗi, gọi phương thức charAt() trên chuỗi, truyền cho nó 0 làm tham số - str. charAt(0) . Phương thức trả về một chuỗi mới chứa ký tự tại chỉ mục đã chỉ định.

Làm cách nào để lấy 3 chữ cái đầu tiên của chuỗi trong JavaScript?

Sử dụng chuỗi. slice() để lấy ba ký tự đầu tiên của một chuỗi , e. g. const first3 = str. lát (0, 3);. Phương thức slice sẽ trả về một chuỗi mới chứa ba ký tự đầu tiên của chuỗi ban đầu.

Làm cách nào để lấy 2 chữ cái đầu tiên của chuỗi trong JavaScript?

Để lấy hai ký tự đầu tiên của một chuỗi trong JavaScript, gọi phương thức slice() trên chuỗi, lần lượt truyền 0 và 2 làm đối số thứ nhất và thứ hai. For example, str. slice(0, 2) returns a new string containing the first two characters of str .