Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การหาความยาวคำก่อนหน้าคำสุดท้ายในประโยคด้วย JavaScript

บทความนี้สาธิตฟังก์ชันนับความยาวของคำที่ 2 จากท้ายในประโยค (คั่นด้วยช่องว่าง)

ตัวอย่าง

str = 'this is an example string' -> output: 7 ('example')

ตัวอย่างโค้ด

const str = 'this is an example string';

const countSecondLast = (str = '') => {
  const strArr = str.split(' ');
  const { length: len } = strArr;
  if (len <= 2) {
    return 0;
  }
  const el = strArr[len - 2];
  const { length } = el;
  return length;
};

console.log(countSecondLast(str));

ผลลัพธ์

7

คำอธิบาย

split ด้วย space ได้อาร์เรย์คำ หากมีคำ <= 2 คืน 0 มิฉะนั้นคืนความยาวของ index length-2

Time: O(n), Space: O(n)