在 JavaScript 中查詢句子的倒數第二個單詞的長度
一句句子只是一串字串,其中包含由空格連線的單詞。我們需要編寫一個 JavaScript 函式,該函式接受一個這樣的句子字串作為輸入,並計算字串中倒數第二個單詞的字元數。如果字串包含不超過 2 個單詞,則我們的函式應返回 0。
例如 -
如果輸入字串為 -
const str = 'this is an example string';
則輸出應為 -
const output = 7;
因為“example”中的字元數為 7。
示例
以下是程式碼 -
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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP