Without further ado, let's just look at the code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>JS writing method that exceeds text with ellipses</title></head><body><script> function cutString(str, len) { //The length of the Chinese character read by the length attribute is 1 if(str.length*2 <= len) { return str; } var strlen = 0; var s = ""; for(var i = 0;i < str.length; i++) { s = s + str.charAt(i); if (str.charCodeAt(i) > 128) { strlen = strlen + 2; if(strlen >= len){ return s.substring(0,s.length-1) + "..."; } } else { strlen = strlen + 1; if(strlen >= len){ return s.substring(0,s.length-1) + "..."; } } else { strlen = strlen + 1; if(strlen >= len){ return s.substring(0,s.length-2) + "..."; } } } return s;}window.onload=function(){ var str = document.getElementById('cut_str').innerHTML; var s=cutString(str,15); document.getElementById('cut_str').innerHTML=s;}</script><div><p id="cut_str">JS writing method that exceeds text is replaced by ellipses. </p></div></body></html>Implementation renderings
Summarize
In fact, the main thing is to use the substring method of js. It is still very simple to implement this function, but it is very practical. The above is the entire content of this article. I hope this article will be of some help to everyone.