How can I make sure my javascript removes spaces before adding "..."

I have a string variable that looks like this:

Årets upplaga av Storsjöcupen, en fotbollsturnering i Östersund för ungdomar, fick en trist avrundning när anhängare to ett norskt pojklag anklagades för att ha farit ut i rasistiska och könsordskryddadeläämäländäämälen.

When my javascript is executed, it turns the string into:

Årets upplaga av Storsjöcupen, en fotbollsturnering i Östersund för ungdomar, fick en trist avrundning när anhängare to ett norskt pojklag ...

If you see three "...", this is the space that I do not want to have.

I want this to be:

pojklag ...

My javascript looks like this:

function TrimLength(text, maxLength) { text = $.trim(text); if (text.length > maxLength) { text = text.substring(0, maxLength - ellipsis.length) return text.substring(0, text.lastIndexOf(" ")) + ellipsis; } else return text; } 

 $(document).ready(function () { $(".text").each(function () { var text = $(this).text(); $(this).text(TrimLength(text, 150)); }); 

How can I make sure the space is removed?

Any help is appreciated.

+4
source share
2 answers

Just change this line:

 return text.substring(0, text.lastIndexOf(" ") - 1) + ellipsis; 

Your code finds the last space and removes everything after it. Just make the length before substring one character shorter and you will also remove the last space.

+5
source

I would do it like this:

 function trimLength( text, maxLength ) { text = $.trim( text ); if( text.length <= maxLength ) return text; return text .slice( 0, maxLength - ellipsis.length ) .replace( /\s+\S*$/, '' ) + ellipsis; } 

This should handle all cases mentioned in other comments, including a line with no spaces in it, as well as a line with more than one consecutive space where it breaks.

Also, as a suggestion, I took the liberty of changing the function name from TrimLength to TrimLength , because it is not a constructor. Idiomatic JavaScript starts the names of constructors with a capital letter and other functions and variables with a lower case letter.

+1
source

Source: https://habr.com/ru/post/1490594/


All Articles