Cameron
Cameron

Reputation: 28793

ASP.NET MVC SubString help

I have an ASP.NET MVC app that shows news articles and for the main paragraph I have a truncate and HTML tag stripper. e.g. <p><%= item.story.RemoveHTMLTags().Truncate() %></p>

The two functions are from an extension and are as follows:

public static string RemoveHTMLTags(this string text)
{
    return Regex.Replace(text, @"<(.|\n)*?>", string.Empty);
}
public static string Truncate(this string text)
{
    return text.Substring(0, 200) + "...";
}

However when I create a new article say with a story with only 3-4 words it will throw this error: Index and length must refer to a location within the string. Parameter name: length

What is the problem? Thanks

Upvotes: 3

Views: 5565

Answers (2)

Chandu
Chandu

Reputation: 82903

Change your truncate function to this:

public static string Truncate(this string text) 
{     
    if(text.Length > 200)
    {
        return text.Substring(0, 200) + "..."; 
    }
    else
    {
        return text;
    }

} 

A much more useful version would be

public static string Truncate(this string text, int length) 
{     
    if(text.Length > length)
    {
        return text.Substring(0, length) + "..."; 
    }
    else
    {
        return text;
    }

} 

Upvotes: 7

womp
womp

Reputation: 116977

The problem is that your length parameter is longer than the string, so it's throwing an exception just as the function documentation states.

In other words, if the string isn't 200 characters long, Substring(0, 200) doesn't work.

You need to dynamically determine the substring based on the original string's length. Try:

return text.Substring(0, (text.Length > 200) : 200 ? text.Length);

Upvotes: 1

Related Questions