我正在寻找一种从字符串中提取单词数量的方法。
例如,我有以下字符串。
var word = "Customer Courseware Development and OTB Creation - Learning Center Set Up"
var value = 4;
根据上面的值,我想得到字符串中的最后4个单词,即"学习中心设置"
到目前为止,我所做的就是在下面我只得到了#34; Up"字。
var wordlength = 4;
var str = "Customer Courseware Development and OTB Creation - Learning Center Set Up"
var parts = str.substring(str.lastIndexOf(" ") - length);
console.log(parts);
答案 0 :(得分:1)
您可以将Array#slice()
与join()
var wordlength = 4;
var str = "Customer Courseware Development and OTB Creation - Learning Center Set Up";
var parts = str.split(' ');
var newString = parts.slice(parts.length-wordlength, parts.length).join(" ");
console.log(newString);

答案 1 :(得分:0)
你可以这样做。使用' '
拆分句子,然后从parts.length - wordlength
开始切片。
var wordlength = 4;
var str = "Customer Courseware Development and OTB Creation - Learning Center Set Up"
var parts = str.split(' ');
var newStr = parts.slice(parts.length-wordlength, parts.length).join(' ');
console.log(newStr);
答案 2 :(得分:-1)
使用:
var word = "Customer Courseware Development and OTB Creation - Learning Center Set Up"
var wordlength = 4
var words = word.split(" ")
var result = words.slice(words.length - wordlength)
输出:
Array [ "Learning", "Center", "Set", "Up" ]
然后从上面的数组中创建一个字符串:
result.join(" ")
结果:
"Learning Center Set Up"