受欢迎的博客标签

How to truncate string without breaking a word in half

Published

http://geekswithblogs.net/hmloo/archive/2012/02/19/how-to-truncate-string-without-breaking-a-world-in-half.aspx  

How to Remove or Truncate or Strip the HTML Tags in a String Variable in C#.

This little code snippet will help us to remove the HTML tags contained in a string variable using Regular Expression.  

protected void Page_Load(object sender, EventArgs e)   

{       

string str = "<b>I Love Dotnet</b>";       

Response.Write(RemoveHTMLTags(str));   

}    

public string RemoveHTMLTags(string source)   

{       

string expn = "<.*?>";       

return Regex.Replace(source, expn, string.Empty);   

}  

Include System.Text.RegularExpressions namespace for the above code to work.   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, <span class="skimlinks-unlinked">Math.min(str.length</span>, 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, <span class="skimlinks-unlinked">Math.Min(str.Length</span>, str.LastIndexOf(" ") == -1 ? 0 : str.LastIndexOf(" ")));         

str = str + suffix;     

}     

return <span class="skimlinks-unlinked">str.Trim</span>();

}

public static string Truncate(string str, int maxLength, string suffix)

{     

if (str.Length > maxLength)     

{         

var words = <span class="skimlinks-unlinked">str.Split(new</span>[] { ' ' }, 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 <span class="skimlinks-unlinked">str.Trim</span>();

} .