Geeks With Blogs
hmloo's World of .NET

Sometimes you need to shorten a long string to certain length without cutting the final word in half and add custom string such as 3 dots to the end, It will moves the pointer up to the previous space, if the limit finished within a word.

Here I listed 3 functions may help you.

Javascript

function Truncate(str, maxLength, suffix)
{
    if(str.length > maxLength)
    {
        str = str.substring(0, maxLength + 1); 
        str = str.substring(0, Math.min(str.length, str.lastIndexOf(" ")));
        str = str + suffix;
    }
    return str;
}

C#

public static string Truncate(string str, int maxLength, string suffix)
{
    if (str.Length > maxLength)
    {
        str = str.Substring(0, maxLength + 1);
        str = str.Substring(0, Math.Min(str.Length, str.LastIndexOf(" ") == -1 ? 0 : str.LastIndexOf(" ")));
        str = str + suffix;
    }
    return str.Trim();
}
public static string Truncate(string str, int maxLength, string suffix)
{
    if (str.Length > maxLength)
    {
        var words = str.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        var sb = new StringBuilder();
        for (int i = 0; sb.ToString().Length + words[i].Length <= maxLength; i++)
        {
            sb.Append(words[i]);
            sb.Append(" ");
        }
        str = sb.ToString().TrimEnd(' ') + suffix;
    }
    return str.Trim();
}
Posted on Sunday, February 19, 2012 1:32 PM | Back to top


Comments on this post: How to truncate string without breaking a word in half

# re: How to truncate string without breaking a word in half
Requesting Gravatar...
How verbose.

var r = new RegExp('^(.{' + maxLength.toString() + '}\S*).*$')
return str.replace(r,"$1") + suffix
Left by Iļja on Nov 20, 2012 12:30 PM

# re: How to truncate string without breaking a word in half
Requesting Gravatar...
Nice code snippet worked well for me
Thanks for the Help
Left by Balakrishnan.S on Aug 05, 2013 6:35 PM

# re: How to truncate string without breaking a word in half
Requesting Gravatar...
I get a syntax error in your javascript code, therefore does not work and it's useless.

NOTE: Your "leave your email address" link does not work either.

Please fix all these issues, otherwise your blog is USELESS. Just saying !

thanks !
Left by nicachipal on Oct 11, 2014 5:40 AM

Your comment:
 (will show your gravatar)


Copyright © hmloo | Powered by: GeeksWithBlogs.net