我想使用JavaScript截断带省略号的文本或行

时间:2011-01-15 14:58:05

标签: javascript string truncate

我正在寻找一个简单的脚本,可以使用省略号(...)

截断字符串

我想截断'this is a very long string''this is a ve...'

之类的内容

我不想使用CSS或PHP。

11 个答案:

答案 0 :(得分:70)

function truncate(input) {
   if (input.length > 5)
      return input.substring(0,5) + '...';
   else
      return input;
};

或更新式的样式JS ......

const truncate = (input) => input.length > 5 ? `${input.substring(0, 5)}...` : input;

答案 1 :(得分:32)

KooiInc对此有一个很好的答案。总结一下:

String.prototype.trunc = 
      function(n){
          return this.substr(0,n-1)+(this.length>n?'…':'');
      };

现在你可以做到:

var s = 'not very long';
s.trunc(25); //=> not very long
s.trunc(5); //=> not...

如果你喜欢它作为一个功能,按照@ AlienLifeForm的评论:

function truncateWithEllipses(text, max) 
{
    return text.substr(0,max-1)+(text.length>max?'…':''); 
}

完全归功于KooiInc

答案 2 :(得分:6)

类似的东西:

var line = "foo bar lol";
line.substring(0, 5) + '...' // gives "foo b..."

答案 3 :(得分:4)

最简单灵活的方式:JSnippet DEMO

功能样式:

function truncString(str, max, add){
   add = add || '...';
   return (typeof str === 'string' && str.length > max ? str.substring(0,max)+add : str);
};

原型:

String.prototype.truncString = function(max, add){
   add = add || '...';
   return (this.length > max ? this.substring(0,max)+add : this);
};

用法:

str = "testing with some string see console output";

//By prototype:
console.log(  str.truncString(15,'...')  );

//By function call:
console.log(  truncString(str,15,'...')  );

答案 4 :(得分:4)

这会将它限制为您想要限制的许多行并且响应

没有人建议的想法,根据元素的高度进行操作,然后从那里剥离。

小提琴 - https://jsfiddle.net/hutber/u5mtLznf/< - ES6版

但基本上你想要抓住元素的行高,循环遍历所有文本并在某个行高处停止:

#truncateme {
   width: auto; This will be completely dynamic to the height of the element, its just restricted by how many lines you want it to clip to
}

<强> CSS

    String inputfilepath = "C:/tmp/template.pptx";

            PresentationMLPackage presentationMLPackage = 
                (PresentationMLPackage)OpcPackage.load(new java.io.File(inputfilepath));

        for (int i=0 ; i<presentationMLPackage.getMainPresentationPart().getSlideCount(); i++) {

            SlidePart slidePart = presentationMLPackage.getMainPresentationPart().getSlide(i);

            SlideLayoutPart slideLayoutPart = slidePart.getSlideLayoutPart();

            //System.out.println(slp.getSourceRelationships().get(0).getTarget());
            System.out.println(slidePart.getPartName().getName());

            String layoutName = slideLayoutPart.getJaxbElement().getCSld().getName(); 

            System.out.println("layout: " + slideLayoutPart.getPartName().getName() + " with cSld/@name='" + layoutName + "'");

            System.out.println("Master: " + slideLayoutPart.getSlideMasterPart().getPartName().getName());

}

答案 5 :(得分:4)

用于防止单词中间或标点符号后面的点。

let parseText = function(text, limit){
if (text.length > limit)
    for (let i = limit; i > 0; i--){
        if(text.charAt(i) === ' ' && (text.charAt(i-1) != ','||text.charAt(i-1) != '.'||text.charAt(i-1) != ';')) {
            return text.substring(0, i) + '...';
        }
    }
else
    return text;
};

答案 6 :(得分:3)

这会将省略号放在行的中心:

function truncate( str, max, sep ) {

    // Default to 10 characters
    max = max || 10;

    var len = str.length;
    if(len > max){

        // Default to elipsis
        sep = sep || "...";

        var seplen = sep.length;

        // If seperator is larger than character limit,
        // well then we don't want to just show the seperator,
        // so just show right hand side of the string.
        if(seplen > max) {
            return str.substr(len - max);
        }

        // Half the difference between max and string length.
        // Multiply negative because small minus big.
        // Must account for length of separator too.
        var n = -0.5 * (max - len - seplen);

        // This gives us the centerline.
        var center = len/2;

        var front = str.substr(0, center - n);
        var back = str.substr(len - center + n); // without second arg, will automatically go to end of line.

        return front + sep + back;

    }

    return str;
}

console.log( truncate("123456789abcde") ); // 123...bcde (using built-in defaults) 
console.log( truncate("123456789abcde", 8) ); // 12...cde (max of 8 characters) 
console.log( truncate("123456789abcde", 12, "_") ); // 12345_9abcde (customize the separator) 

例如:

1234567890 --> 1234...8910

A really long string --> A real...string

不完美,但功能齐全。原谅过度评论...对于新手。

答案 7 :(得分:2)

function truncate(string, length, delimiter) {
   delimiter = delimiter || "&hellip;";
   return string.length > length ? string.substr(0, length) + delimiter : string;
};

var long = "Very long text here and here",
    short = "Short";

truncate(long, 10); // -> "Very long ..."
truncate(long, 10, ">>"); // -> "Very long >>"
truncate(short, 10); // -> "Short"

答案 8 :(得分:1)

使用JavaScript的HTML:

<p id="myid">My long long looooong text cut cut cut cut cut</p>

<script type="text/javascript">
var myid=document.getElementById('myid');
myid.innerHTML=myid.innerHTML.substring(0,10)+'...';
</script>

结果将是:

My long lo...

干杯

-G。

答案 9 :(得分:1)

如果要剪切指定长度的字符串并添加点,请使用

// Length to cut
var lengthToCut = 20;

// Sample text
var text = "The quick brown fox jumps over the lazy dog";

// We are getting 50 letters (0-50) from sample text
var cutted = text.substr(0, lengthToCut );
document.write(cutted+"...");

或者,如果你想减少长度,但要使用单词计数:

// Number of words to cut
var wordsToCut = 3;

// Sample text
var text = "The quick brown fox jumps over the lazy dog";

// We are splitting sample text in array of words
var wordsArray = text.split(" ");

// This will keep our generated text
var cutted = "";
for(i = 0; i < wordsToCut; i++)
 cutted += wordsArray[i] + " "; // Add to cutted word with space

document.write(cutted+"...");
祝你好运......

答案 10 :(得分:1)

试试这个

function shorten(text, maxLength, delimiter, overflow) {
  delimiter = delimiter || "&hellip;";
  overflow = overflow || false;
  var ret = text;
  if (ret.length > maxLength) {
    var breakpoint = overflow ? maxLength + ret.substr(maxLength).indexOf(" ") : ret.substr(0, maxLength).lastIndexOf(" ");
    ret = ret.substr(0, breakpoint) + delimiter;
  }
  return ret;
}

$(document).ready(function() {
  var $editedText = $("#edited_text");
  var text = $editedText.text();
  $editedText.text(shorten(text, 33, "...", false));
});

在Codepen上查看工作示例 http://codepen.io/Izaias/pen/QbBwwE