我正在尝试使函数告诉我有多少个单词少于3个字母。
例如,“明天将下雨。请带上雨伞”
在这句话中,只有“ be”和“ so”如此相等。任何帮助,将不胜感激。
function (stri){
return ("less than 3 ").length;
}
(我的目标是尽可能使用\ w(正则表达式)。)
最佳答案
如果您使用lodash,则可以执行以下操作...
<script src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
<script>
// create a function to call with your string and the min size of the word
function countSmalls(s,min) {
// split by non word characters
return _.where(s.split(/\W/),function(v,i,l){
// return true or false to satisfy the callback, all *truthy* values are added to the return value of _.where
return v && v.length < min;
}).length;
}
// create some text
var lorem = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.";
// call your function
countSmalls(lorem,3); // 24 (words that are < 3 characters)
</script>
关于javascript - Google JavaScript电子表格,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22677293/