jQuery返回一个没有逗号的字符串的前5个单词
I'm trying to return the first 5 words of a string in a readable format, no "" or commas separating words. I'm not sure if its a regex thing or what, but I can't figure it out although its probably simple. Thanks!
我试图以可读格式返回字符串的前5个单词,没有“”或逗号分隔单词。我不确定它是一个正则表达式的东西还是什么,但我想不出来虽然它可能很简单。谢谢!
See what I have thus far: http://jsfiddle.net/ccnokes/GktTd/
看看我到目前为止:http://jsfiddle.net/ccnokes/GktTd/
This is the function I'm using:
这是我正在使用的功能:
function getWords(string){
var words = string.split(/\s+/).slice(1,5);
return words;
}
3 个解决方案
#1
30
The only thing you are missing is a join()
你唯一缺少的是一个join()
Try this:
尝试这个:
function getWords(str) {
return str.split(/\s+/).slice(0,5).join(" ");
}
This will do something like:
这将做类似的事情:
var str = "This is a long string with more than 5 words.";
console.log(getWords(str)); // << outputs "This is a long string"
Take a look at this link for a further explanation of the .join()
. function in javascript. Essentially - if you don't supply an argument, it uses the default delimiter ,
, whereas if you supply one (as I'm doing in the above example, by providing " "
- it will use that instead. This is why the output becomes the first 5 words, separated by a space between each.
请查看此链接以获取.join()的进一步说明。在javascript中的功能。本质上 - 如果你不提供参数,它使用默认分隔符,而如果你提供一个(正如我在上面的例子中做的那样,通过提供“” - 它将使用它。这就是为什么输出成为前5个单词,每个单词之间用空格分隔。
更多相关文章
- jquery做的表格分页功能
- [置顶] JavaWeb JQuery实现记住我功能
- jquery datepicker,即使是另一个具有共享导入功能的jsp也没有响应
- JQuery的一些基本功能代码(CH1&2)
- 网页标签功能插: jQuery tags input 翻译api
- 键盘功能无法处理数据表搜索
- [求助]如何用JQuery来实现Ctrl+Space完成输入特定字符提示的自动
- JQuery自动完成功能不会显示所有结果
- 目前最好用的“点击复制”功能,兼容主流浏览器