在JavaScript中查找句子中倒数第二个单词的长度
句子只是一个字符串,其中包含由空格连接的字符串(称为单词)。我们需要编写一个JavaScript函数,该函数接受一个这样的句子字符串,并计算该字符串倒数第二个单词中的字符数。如果字符串包含的单词数不超过2个,则我们的函数应返回0。
例如-
如果输入字符串是-
const str = 'this is an example string';
那么输出应该是-
const output = 7;
因为示例中的字符数是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
热门推荐
10 感谢韩语老师祝福语简短
11 升职文案高级祝福语简短
12 花童结婚祝福语大全简短
13 向国庆送祝福语简短
14 什么寄语简短祝福语女生
15 客户回礼祝福语大全简短
16 女孩生日祝福语简短创意
17 家长回复节日祝福语简短
18 给外婆敬酒祝福语简短