How to Get First X Chars from a String, Without Cutting Off the Last Word

How to get first x chars from a string, without cutting off the last word?

You can use the wordwrap() function, then explode on newline and take the first part:

$str = wordwrap($str, 28);
$str = explode("\n", $str);
$str = $str[0] . '...';

Trim String by so many characters but do not cut off last word

I use the following method:

''' <summary>
''' Creates a shortend version of a string, with optional follow-on characters.
''' </summary>
''' <param name="stringToShorten">The string you wish to shorten.</param>
''' <param name="newLength">
''' The new length you want the string to be (nearest whole word).
''' </param>
''' <param name="isAbsoluteLength">
''' If set to <c>true</c> the string will be no longer than <i>newLength</i>.
''' and will cut off mid-word.
''' </param>
''' <param name="stringToAppend">
''' What you'd like on the end of the shorter string to indicate truncation.
''' </param>
''' <returns>The shorter string.</returns>
Public Shared Function ShortenString(stringToShorten As String, newLength As Integer, isAbsoluteLength As Boolean, stringToAppend As String) As String
If Not isAbsoluteLength AndAlso (newLength + stringToAppend.Length > stringToShorten.Length) Then
' requested length plus append will be longer than original
Return stringToShorten
ElseIf isAbsoluteLength AndAlso (newLength - stringToAppend.Length > stringToShorten.Length) Then
' requested length minus append will be longer than original
Return stringToShorten
Else
Dim cutOffPoint As Integer

If Not isAbsoluteLength Then
' Find the next space after the newLength.
cutOffPoint = stringToShorten.IndexOf(" ", newLength)
Else
' Just cut the string off at exactly the length required.
cutOffPoint = newLength - stringToAppend.Length
End If

If cutOffPoint <= 0 Then
cutOffPoint = stringToShorten.Length
End If

Return stringToShorten.Substring(0, cutOffPoint) + stringToAppend
End If
End Function

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(" ")))

Make string shorter. Cut it by the last word

This should work:

$str = "i have google too";
$strarr = explode(" ", $str);

$res = "";

foreach($strarr as $k)
{
if (strlen($res.$k)<10)
{
$res .= $k." ";
}
else
{
break;
};
}

echo $res;

http://codepad.org/NP9t4IRi

This regex is cutting off the last word in the string even though strlen is within acceptable range

Using substr and strrpos

if (strlen($theExcerpt) > 156) {
$theExceprt = substr($theExcerpt, 0, 156);
$theExcerpt = substr($theExcerpt, 0, strrpos($theExcerpt, ' '));
$theExcerpt .= '...';
}

PHP Make an excerpt by cutting the string on the last space after x characters

A simple (and fast) way to cut a string to a fixed number of characters is with preg_replace:

$string = 'Стихи похожи на людей: помнят прошлое и ничего не знают о будущем, хотят жить вечно, a страница уже перелистывается.';
$excerpt = preg_replace('/^(.{1,110})\s.*$/u', '$1...', $string);
echo $excerpt;

Output:

Стихи похожи на людей: помнят прошлое и ничего не знают о будущем, хотят жить вечно, a страница уже...

The regex works by looking for some number of characters ^(.{1,110})\s (from 1 to 110) from the start of a string and up to a space character. Since the quantifier is greedy it takes as many characters as it can. Those characters are captured in a group. The rest of the string is then matched by .*$, and the whole string is replaced by the first capture group and three .'s ($1...), giving just the first portion as desired. The u flag on the regex means it will count unicode characters correctly. To adjust the length of the excerpt, simply change the 110 to whatever length you need.

Regex101 demo

Edit

The regex can also be modified to strip off any non-word characters (so you don't end up with the quick brown fox,...) by modifying it to insist that the last character of the capture group is a word character and then allowing the following character to be a non-word character:

$string = 'Стихи похожи на людей: помнят прошлое и ничего не знают о будущем, хотят жить вечно, a страница уже перелистывается.';
$excerpt = preg_replace('/^(.{1,23}\w)\W.*$/u', '$1...', $string);
echo $excerpt;

Output:

Стихи похожи на людей...

Updated demo

How to remove the last word in a string using JavaScript

Use:

var str = "I want to remove the last word.";
var lastIndex = str.lastIndexOf(" ");

str = str.substring(0, lastIndex);

Get the last space and then get the substring.

How do I chop/slice/trim off last character in string using Javascript?

You can use the substring function:

let str = "12345.00";str = str.substring(0, str.length - 1);console.log(str);


Related Topics



Leave a reply



Submit