Truncate string to keep the first n words
This code truncates the text to keep the first n words, while keeping the rest of the text unchanged.
For example, you want to restrict users from typing/pasting too many words of text; you don't want to be changing what they typed aside from truncating.
var words = text.split(/(?=\s)/gi);
var indexToStop = words.length;
var count = 0;
for (var i = 0; i < words.length && count <= n; i++) {
if (words[i].trim() != "") {
if (++count > n)
indexToStop = i;
}
}
var truncated = words.slice(0, indexToStop).join('');
Truncate string to the first n words
n = 3
str = "your long long input string or whatever"
str.split[0...n].join(' ')
=> "your long long"
str.split[0...n] # note that there are three dots, which excludes n
=> ["your", "long", "long"]
How to truncate a string after n words in Java?
I found a way to do it using the java.text.BreakIterator class:
private static String truncateAfterWords(int n, String s) {
if (s == null) return null;
BreakIterator wb = BreakIterator.getWordInstance();
wb.setText(s);
int pos = 0;
for (int i = 0; i < n && pos != BreakIterator.DONE && pos < s.length();) {
if (Character.isLetter(s.codePointAt(pos))) i++;
pos = wb.next();
}
if (pos == BreakIterator.DONE || pos >= s.length()) return s;
return s.substring(0, pos);
}
Truncate character strings after first N characters
There is already a packaged function for this operation. Try str_trunc()
from the stringr package, setting the width to 13 (10 chars + 3 dots).
stringr::str_trunc(a, 13)
# [1] "AMS" "CCD" "TCGGCKGTPG..." "NOK"
# [5] "THIS IS A ..." "JSQU909LPPLU"
Truncate a string to first n characters of a string and add three dots if any characters are removed
//The simple version for 10 Characters from the beginning of the string
$string = substr($string,0,10).'...';
Update:
Based on suggestion for checking length (and also ensuring similar lengths on trimmed and untrimmed strings):
$string = (strlen($string) > 13) ? substr($string,0,10).'...' : $string;
So you will get a string of max 13 characters; either 13 (or less) normal characters or 10 characters followed by '...'
Update 2:
Or as function:
function truncate($string, $length, $dots = "...") {
return (strlen($string) > $length) ? substr($string, 0, $length - strlen($dots)) . $dots : $string;
}
Update 3:
It's been a while since I wrote this answer and I don't actually use this code any more. I prefer this function which prevents breaking the string in the middle of a word using the wordwrap
function:
function truncate($string,$length=100,$append="…") {
$string = trim($string);
if(strlen($string) > $length) {
$string = wordwrap($string, $length);
$string = explode("\n", $string, 2);
$string = $string[0] . $append;
}
return $string;
}
How can I truncate a string to the first 20 words in PHP?
function limit_text($text, $limit) {
if (str_word_count($text, 0) > $limit) {
$words = str_word_count($text, 2);
$pos = array_keys($words);
$text = substr($text, 0, $pos[$limit]) . '...';
}
return $text;
}
echo limit_text('Hello here is a long sentence that will be truncated by the', 5);
Outputs:
Hello here is a long ...
Shorten string without cutting words in JavaScript
If I understand correctly, you want to shorten a string to a certain length (e.g. shorten "The quick brown fox jumps over the lazy dog"
to, say, 6 characters without cutting off any word).
If this is the case, you can try something like the following:
var yourString = "The quick brown fox jumps over the lazy dog"; //replace with your string.
var maxLength = 6 // maximum number of characters to extract
//trim the string to the maximum length
var trimmedString = yourString.substr(0, maxLength);
//re-trim if we are in the middle of a word
trimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")))
Related Topics
CSV - Unquoted Fields Do Not Allow \R or \N (Line 2)
Paperclip Amazon S3 Setup with Heroku
Vi Input Mode in Command Line Matlab
How to Create Md5 Hash with Hmac Module in Ruby
Ruby $Stdin.Gets Without Showing Chars on Screen
Deleting While Iterating in Ruby
How to Assign Multiple Values to a Hash Key
How to Test for a Redirect with Rspec and Capybara
Nokogiri Error When Running Bundle Install
Strictly Convert String to Integer (Or Nil)
What Is the Community-Preferred Ruby Unit Testing Framework
Rails: Find Rows Without Connection in Habtm Relation
Rails Console Not Working on Server
Ruby Split String by Repeating Characters or a Space