Display only 10 characters of a long string?

前端 未结 12 2090
臣服心动
臣服心动 2020-12-13 01:19

How do I get a long text string (like a querystring) to display a maximum of 10 characters, using JQuery?

Sorry guys I\'m a novice at JavaScript & JQuery :S

12条回答
  •  一向
    一向 (楼主)
    2020-12-13 02:02

    @jolly.exe

    Nice example Jolly. I updated your version which limits the character length as opposed to the number of words. I also added setting the title to the real original innerHTML , so users can hover and see what is truncated.

    HTML

    a reallly really really long titleasdfasdfasdfasdfasdfasdfasdfadsf

    JS

     function cutString(id){    
         var text = document.getElementById(id).innerHTML;         
         var charsToCutTo = 30;
            if(text.length>charsToCutTo){
                var strShort = "";
                for(i = 0; i < charsToCutTo; i++){
                    strShort += text[i];
                }
                document.getElementById(id).title = "text";
                document.getElementById(id).innerHTML = strShort + "...";
            }            
         };
    
    cutString('stuff'); 
    

提交回复
热议问题