[英]What is the best way to get the first x number of words from a string javascript
With out using jquery, what is the easiest way to do this? 在不使用jquery的情况下,最简单的方法是什么? If I have a string containing 600 words, and I want only the first 100 or so words and then trail off with:
...
what is the easiest way to do this? 如果我有一个包含600个单词的字符串,而我只想要前100个左右的单词,然后使用:
...
最简单的方法是什么?
I found: replace(/(([^\\s]+\\s\\s*){40})(.*)/,"$1…");
我发现:
replace(/(([^\\s]+\\s\\s*){40})(.*)/,"$1…");
But I don' understand regex enough to know if this is right or not. 但是我对正则表达式的理解不够,无法知道这是否正确。
@dfsq's solution is a nice straight forward one, but in the interest of learning :) @dfsq的解决方案是一个很好的直截了当的解决方案,但出于学习的目的:)
To try and understand regexes, I would advice looking at the flow-chart-alike visualisation that Debuggex gives you, and experiment with substitution on Regex101 . 为了尝试理解正则表达式,我建议您看一下Debuggex为您提供的类似于流程图的可视化,并尝试对Regex101进行替换。 (links contain the regex unaltered from your question)
(链接包含您的问题未更改的正则表达式)
I would make some small modifications: 我会做一些小的修改:
.
.
doesn't match new-lines, one way to do that is to match [\\s\\S]
in stead, which matches absolutely every character [\\s\\S]
,它绝对匹配每个字符 [^\\s]+\\s\\s*
can be untangled and optimized to \\S+\\s+
, but I would turn it around and make it \\s*\\S+
so that the ...
comes after the last word without a space in between. [^\\s]+\\s\\s*
可以理顺并优化为\\S+\\s+
,但是我会把它改成\\s*\\S+
以便...
出现在最后一个单词之后,而没有之间的空间。 Which would result in this: 这将导致以下结果:
((\s*\S+){40})([\s\S]*)
That's quite simple I guess (I don't know if this is the best way) ! 我猜那很简单(我不知道这是否是最好的方法)!
for(var i=1;i <= numberOfWords;i++) {
var word = mystr.substr(0,mystr.indexOf(' ')+1).trim();
arrayOfWords.push(word);
mystr = mystr.substr(mystr.indexOf(' '),mystr.length-1).trim();
}
Try for yourself: http://jsfiddle.net/fourat05/w386mxaa/ 自己尝试: http : //jsfiddle.net/fourat05/w386mxaa/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.