Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate sentence to a certain number of words

Tags:

javascript

How can a sentence be truncated to a certain number of words (NB. not letters)?

I thought to use split(" "), but then how do I count out words?

For example:

  • Javascript word count cut off => Javascript word count
  • Want better search results? See our search tips! => Want better search
like image 744
fish man Avatar asked Sep 10 '11 21:09

fish man


People also ask

How can I truncate a string to the first 20 words in PHP?

use PHP tokenizer function strtok() in a loop.


1 Answers

You can use split [MDN] and join [MDN].

"Want better search results? See our search tips".split(" ").splice(0,3).join(" ")
like image 100
Amir Raminfar Avatar answered Sep 20 '22 15:09

Amir Raminfar