Javascript 只显示长字符串的 10 个字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3414916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:32:05  来源:igfitidea点击:

Display only 10 characters of a long string?

javascriptjquerysubstringstring-length

提问by Nasir

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

如何使用 JQuery 获取最多显示 10 个字符的长文本字符串(如查询字符串)?

Sorry guys I'm a novice at JavaScript & JQuery :S
Any help would be greatly appreciated.

对不起,我是 JavaScript 和 JQuery 的新手:S
任何帮助将不胜感激。

回答by Sebs

If I understand correctly you want to limit a string to 10 characters?

如果我理解正确,您想将字符串限制为 10 个字符吗?

var str = 'Some very long string';
if(str.length > 10) str = str.substring(0,10);

Something like that?

类似的东西?

回答by Giuseppe Accaputo

And here's a jQuery example:

这是一个 jQuery 示例:

HTML text field:

HTML 文本字段:

<input type="text" id="myTextfield" />

jQuery code to limit its size:

用于限制其大小的 jQuery 代码:

var elem = $("#myTextfield");
if(elem) elem.val(elem.val().substr(0,10));

As an example, you could use the jQuery code above to restrict the user from entering more than 10 characters while he's typing; the following code snippet does exactly this:

例如,您可以使用上面的 jQuery 代码限制用户在打字时输入超过 10 个字符;以下代码片段正是这样做的:

$(document).ready(function() {
    var elem = $("#myTextfield");
    if (elem) {
        elem.keydown(function() {
            if (elem.val().length > 10)
                elem.val(elem.val().substr(0, 10));
        });
    }            
});


Update: The above code snippet was only used to show an example usage.

更新:上面的代码片段仅用于显示示例用法。

The following code snippet will handle you issue with the DIV element:

以下代码片段将处理您与 DIV 元素有关的问题:

$(document).ready(function() {
    var elem = $(".tasks-overflow");
    if(elem){
        if (elem.text().length > 10)
                elem.text(elem.text().substr(0,10))
    }
});

Please notethat I'm using textinstead of valin this case, since the valmethod doesn't seem to work with the DIV element.

请注意,在这种情况下我使用的是text而不是val,因为该val方法似乎不适用于 DIV 元素。

回答by Tatranskymedved

Creating own answer, as nobody has considered that the split might not happened (shorter text). In that case we don't want to add '...' as suffix.

创建自己的答案,因为没有人认为拆分可能不会发生(较短的文本)。在这种情况下,我们不想添加 '...' 作为后缀。

Ternary operator will sort that out:

三元运算符将解决这个问题:

var text = "blahalhahkanhklanlkanhlanlanhak";
var count = 35;

var result = text.slice(0, count) + (text.length > count ? "..." : "");

Can be closed to function:

可以关闭功能:

function fn(text, count){
    return text.slice(0, count) + (text.length > count ? "..." : "");
}

console.log(fn("aognaglkanglnagln", 10));

And expand to helpers class so You can even choose if You want the dots or not:

并扩展到助手类,以便您甚至可以选择是否需要点:

function fn(text, count, insertDots){
    return text.slice(0, count) + (((text.length > count) && insertDots) ? "..." : "");
}

console.log(fn("aognaglkanglnagln", 10, true));
console.log(fn("aognaglkanglnagln", 10, false));

回答by Ranjita Naik

var example = "I am too long string";
var result;

// Slice is JS function
result = example.slice(0, 10)+'...'; //if you need dots after the string you can add

Result variable contains "I am too l..."

结果变量包含“我太……”

回答by Kai Light

('very long string'.slice(0,10))+'...'
// "very long ..."

回答by sje397

html

html

<p id='longText'>Some very very very very very very very very very very very long string</p>

javascript(on doc ready)

javascript(已准备好文档)

var longText = $('#longText');
longText.text(longText.text().substr(0, 10));

If you have multiple words in the text, and want each to be limited to at most 10 chars, you could do:

如果文本中有多个单词,并且希望每个单词最多包含 10 个字符,则可以执行以下操作:

var longText = $('#longText');
var text = longText.text();
var regex = /\w{11}\w*/, match;
while(match = regex.exec(text)) {
    text = text.replace(match[0], match[0].substr(0, 10));
}
longText.text(text);

回答by Ken Ray

What you should also do when you truncate the string to ten characters is add the actual html ellipses entity: &hellip;, rather than three periods.

当您将字符串截断为十个字符时,您还应该添加实际的 html 省略号实体:&hellip;,而不是三个句点。

回答by mraaroncruz

This looks more to me like what you probably want.

在我看来,这更像是您可能想要的。

$(document).ready(function(){
var stringWithShorterURLs = getReplacementString($(".tasks-overflow").text());

function getReplacementString(str){
    return str.replace(/(https?\:\/\/[^\s]*)/gi,function(match){
        return match.substring(0,10) + "..."
    });
}});


you give it your html element in the first line and then it takes the whole text, replaces urls with 10 character long versions and returns it to you. This seems a little strange to only have 3 of the url characters so I would recommend this if possible.


你在第一行给它你的 html 元素,然后它获取整个文本,用 10 个字符长的版本替换 url 并将其返回给你。只有 3 个 url 字符似乎有点奇怪,所以如果可能的话,我会推荐这个。

$(document).ready(function(){
var stringWithShorterURLs = getReplacementString($(".tasks-overflow p").text());

function getReplacementString(str){
    return str.replace(/https?\:\/\/([^\s]*)/gi,function(match){
        return match.substring(0,10) + "..."
    });
}});

which would rip out the http:// or https:// and print up to 10 charaters of www.example.com

这将撕掉 http:// 或 https:// 并打印最多 10 个 www.example.com 的字符

回答by DaFrenzy

@jolly.exe

@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.

乔利的好例子。我更新了您的版本,它限制了字符长度而不是字数。我还添加了将标题设置为真正的原始 innerHTML ,以便用户可以悬停并查看被截断的内容。

HTML

HTML

<div id="stuff">a reallly really really long titleasdfasdfasdfasdfasdfasdfasdfadsf</div> 

JS

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'); 

回答by Alnitak

Although this won't limit the string to exactly 10 characters, why not let the browser do the work for you with CSS:

尽管这不会将字符串限制为恰好 10 个字符,但为什么不让浏览器使用 CSS 为您完成这项工作:

.no-overflow {
    white-space: no-wrap;
    text-overflow: ellipsis;
    overflow: hidden;
}

and then for the table cell that contains the string add the above class and set the maximum permitted width. The result should end up looking better than anything done based on measuring the string length.

然后对于包含字符串的表格单元格添加上述类并设置最大允许宽度。结果看起来应该比基于测量字符串长度所做的任何事情都要好。