3

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

1
  • 1
    out of 164 views I can't be the only person to have found this topic useful and as such upvoted it Commented Jul 26, 2011 at 14:05

2 Answers 2

7

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;
    }

} 
Sign up to request clarification or add additional context in comments.

Comments

1

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);

1 Comment

Okies how can I fix it? Basically want it is supposed to do is truncate stories over 200 characters long. If they are less than 200 then it shouldn't truncate it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.