How to truncate text without cutting words . NET?

Asked

Viewed 624 times

2

I’ve been trying so many ways for days but I haven’t been able to do this script take the value of <h3> and return the text to it truncated.

Javascript:

<script type="text/javascript">
    function truncar() {

        var texto = document.getElementById("texto_noticia");
        var limite = 350;

        if (texto.length > limite) {
            limite--;
            last = texto.substr(limite - 1, 1);
            while (last != ' ' && limite > 0) {
                limite--;
                last = texto.substr(limite - 1, 1);
            }
            last = texto.substr(limite - 2, 1);
            if (last == ',' || last == ';' || last == ':') {
                texto = texto.substr(0, limite - 2) + ' [...]';
            } else if (last == '.' || last == '?' || last == '!') {
                texto = texto.substr(0, limite - 1);
            } else {
                texto = texto.substr(0, limite - 1) + ' [...]';
            }
        }

        alert(texto);
        return (texto);
    }
</script>

HTML:

<h3 id="texto_noticia" class="texto_noticia">
        <%# Eval("Noticia_Conteudo")%>
</h3>

The idea is to bring the content of the news that is in the database through the redepeater, and then make Javascript take the value and truncate the text.

  • 6

    There’s nothing in there. Net.

  • "This text as it would be after truncated, assuming the limit is 15"?

  • @Reginaldorigo For example: "How to truncate text without cutting words." with limit of 15 it would be: "How to truncate text [...]" Although the text limit is in "t" of "text", the function would make it stop only after the word. The problem is being to bring the value and replace it later.

  • It sounds simple. Your routine should read word by word as you add up the total size of it, when you reach the limit or go over to.

  • yes... the code I put above works, in a way... What is giving problem is that the value that will go to text is not working... that command inside H3 serves to fetch a value in the database. The problem is that I can’t get the script to take this value, truncate it and return it to the same H3

  • @Raagatzo, the problem is that the text has already been played to the screen before Javascript could do the truncation. It is easier for you to implement the C# response of the mustache underneath. Otherwise, you will have to find a (not very cool) way to execute the script afterward that html has already received the text from the database.

  • @Ericwu yes... I agree with you... I have tried to make his code bring values of the comic but I’m still having complications for it... but if I can I warn you :D

  • @Raagatzo Did the answer solve your problem? Do you think you can accept it? If you don’t know how you do it, check out [tour]. This would help a lot to indicate that the solution was useful to you and to give an indication that there was a satisfactory solution. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

  • @bigown the problem has not yet been solved, because the truncation I had already managed to do in javascript... I’m having trouble to bring the values of the database, understand? But all of you have helped me...

  • @Raagatzo you could have solved, but what you asked about was this. If the problem was another, ask another question clearly defining the problem. If you want data to be brought from the database, you should ask about it, show what you’ve done about it and what the difficulty is. In this question you asked to do the truncation, it was answered. It is up to you to define whether the answer is satisfactory for this question. Not for other questions. When you ask a new question you can define in the other if one of the answers there is satisfactory for it. I think this one ended.

  • "The idea is to bring the content of the news that is in the database through the Repeater, and then have Javascript take the value and truncate the text." @bigown I specified from the beginning how it would work

  • @bigown fortunately a lot of people answered here, everyone tried to help me, but no answer solved my problem... By my code you can see that javascript truncates the text, just need to know how to bring from the bank table to the java script and then send it to H3... Eric Wu knew how to explain to me why my idea wasn’t working, which helped me in parts, but so far I’m having the problem of starting

  • Como fazer truncamento de texto sem cortar palavras .Net? This is the title. More than 90% of the text talks about truncation. There’s a little bottle at the end about another subject, doesn’t give a single detail about it, nothing to answer that. The question isn’t about that. Do what I’m telling you. Create a new question that focuses on what you’re wondering right now. And put details, because without them, will be closed as not clear. It was answered what you asked. Again, do what I am telling you to get an answer you want. Ask another question.

  • This one has nothing more to do than accept what has been answered and move on to another. There will be no other answer on another subject here. What was placed in this was answered. If you do not want to accept it is your right. I’m thinking it’s better to close as not clear here since you’re insisting you asked something that no one is seeing in the question.

Show 9 more comments

1 answer

3

The secret is to use the LastindexOf(' ') to find out where the last space is. It would be something like this in C#:

if (text.Length <= length) {
    return text;
}
if (length <= ellipsis.Length) {
    return ellipsis.Substring(0, length);
}
text = text.Substring(0, length - ellipsis.Length);
var position = text.LastIndexOf(' ');
position = position < 0 ? 0 : position;
return text.Substring(0, position).Trim(new[] { '.', ',', ';', ':', '!', '?' }) + ellipsis;

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

If you want to do in JS is a simple algorithm conversion. JS has all methods used with identical semantics.

function trimSpecials(text, chars) {
    var result = '';
    for (var i = 0; i < text.length; i++) {
        var isNormal = true;
        for (var j = 0; j < text.length; j++) {
            if (text[i] == chars[j]) {
                isNormal = false;
                break;
            }
        }
        if (isNormal) result += text[i];
    }
    return result;
}

function ellipsis(text, length, ellipsis) {
    ellipsis = typeof ellipsis !== 'undefined' ? ellipsis : '...';
    if (text.length <= length) return text;
    if (length <= ellipsis.length) return ellipsis.substr(0, length);
    text = text.substr(0, length - ellipsis.length);
    var position = text.lastIndexOf(' ');
    position = position < 0 ? 0 : position;
    return trimSpecials(text.substr(0, position), ['.', ',', ';', ':', '!', '?'])  + ellipsis;
}

var texto = "Este é um teste de texto longo que precisa ser truncado com reticências, sem cortar a palavra.";
for (var i = 0; i < texto.length + 1; ++i) console.log(i + ' : ' + ellipsis(texto, i));

I put in the Github for future reference.

  • Thanks, I’ll do the test! I was trying to do in javascript but had already tried in . net tbm

  • Dude... I managed to truncate the text, but there’s a problem... I can only establish the text within the variable! I’m unable to bring the value of the BD table to later truncate it and play in HTML

  • This is another problem, should open a new question specifically about this problem. Take a look and take a look at the [tour]

  • but that was the question at the beginning :x sorry if I was unclear

  • that code I posted also worked... I tried to take advantage of the code in c# q vc posted and try to make it with a select in the bank but it did not work

  • Need another question, I answered what was asked here, if it was something else I wanted to ask it has to be another question.

  • ta, beauty... all right.. but there’s no way to answer right here now that you understand what I need? I’ve been trying to do this for a while because I have no programming experience

  • @bigown, I tried to edit, but I couldn’t: Okay LastInfexOf in place of LastIndexOf.

  • @Ericwu solved, thank you.

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.