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个单词,每个单词之间用空格分隔。

更多相关文章

  1. jquery做的表格分页功能
  2. [置顶] JavaWeb JQuery实现记住我功能
  3. jquery datepicker,即使是另一个具有共享导入功能的jsp也没有响应
  4. JQuery的一些基本功能代码(CH1&2)
  5. 网页标签功能插: jQuery tags input 翻译api
  6. 键盘功能无法处理数据表搜索
  7. [求助]如何用JQuery来实现Ctrl+Space完成输入特定字符提示的自动
  8. JQuery自动完成功能不会显示所有结果
  9. 目前最好用的“点击复制”功能,兼容主流浏览器

随机推荐

  1. Android第七期 - 二维码扫描与生成图
  2. Android Architecture Components(一)Lifec
  3. Android实时获取当前下载速度
  4. CMake 预编译宏定义
  5. android调用系统相机并调整照片大小保存,
  6. Android 继承SQLiteOpenHelper自定义DBHe
  7. Android(安卓)R.java类的手动生成
  8. Android——自定义Log显示
  9. Android最新资源官方下载地址
  10. android 网络语音电话合集 此文为备份