简体   繁体   English

Javascript - 如何截断字符串并在末尾添加三个点

[英]Javascript - How to trucate string and add three dots at end

I have a js string and I wanted to truncate it after 43 char and add three dots (...) at end.我有一个 js 字符串,我想在 43 个字符后截断它并在末尾添加三个点 (...)。 Three dots can be em dash.三个点可以是破折号。

Now the problem is if there was a whitespace at the end with truncated string I wanted to disallow it.现在的问题是,如果在截断的字符串末尾有一个空格,我想禁止它。 Like, the funcation will skipp whitespace at the end while char count and add three dots.就像,函数将在末尾跳过空格,同时 char 计数并添加三个点。

getTruncatedName = (source) => {
         let skippedString = source.trimEnd();
         if(skippedString.length > 43){
             return skippedString.substring(0, 43) + '...';
         }else{
             return source;
         }
     }

Diamond and Mother-of-pearl Circle Pendant in gold plate镀金钻石和珍珠母圆形吊坠

Output: Output:

Diamond and Mother-of-pearl Circle Pendant ...

I want:我想:

Diamond and Mother-of-pearl Circle Pendant...

If i count before... its 42 but i want 43如果我以前数过...它是 42 但我想要 43

Does it always put a space there?它总是在那里放一个空格吗? Or could it be that there is a space at the 43th position and thus that is part of the string and included.或者可能是第 43 个 position 处有一个空格,因此它是字符串的一部分并包含在内。

So maybe try re-trimming again.所以也许再次尝试重新修剪。 Like such像这样

return skippedString.substring(0, 43).trimEnd() + '...';返回 skippedString.substring(0, 43).trimEnd() + '...';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM