Javascript 如何在Javascript中将字符串修剪为N个字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7463658/
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
How to trim a string to N chars in Javascript?
提问by Will
How can I, using Javascript, make a function that will trim string passed as argument, to a specified length, also passed as argument. For example:
我如何使用 Javascript 制作一个函数,将作为参数传递的字符串修剪为指定长度,也作为参数传递。例如:
var string = "this is a string";
var length = 6;
var trimmedString = trimFunction(length, string);
// trimmedString should be:
// "this is"
Anyone got ideas? I've heard something about using substring, but didn't quite understand.
有人有想法吗?我听说过使用 substring 的东西,但不太明白。
回答by Will
Why not just use substring... string.substring(0, 7);
The first argument (0) is the starting point. The second argument (7) is the ending point (exclusive). More info here.
为什么不直接使用子字符串...string.substring(0, 7);
第一个参数 (0) 是起点。第二个参数 (7) 是终点(不包括)。更多信息在这里。
var string = "this is a string";
var length = 7;
var trimmedString = string.substring(0, length);
回答by Jon Lauridsen
Copying Will'scomment into an answer, because I found it useful:
将Will 的评论复制到答案中,因为我发现它很有用:
var string = "this is a string";
var length = 20;
var trimmedString = string.length > length ?
string.substring(0, length - 3) + "..." :
string;
Thanks Will.
谢谢威尔。
And a jsfiddle for anyone who cares https://jsfiddle.net/t354gw7e/:)
对于任何关心https://jsfiddle.net/t354gw7e/ 的人来说,这是一个 jsfiddle :)
回答by xameeramir
I suggest to use an extension for code neatness. Note that extending an internal object prototype could potentially mess with libraries that depend on them.
我建议使用扩展来保持代码整洁。请注意,扩展内部对象原型可能会干扰依赖它们的库。
String.prototype.trimEllip = function (length) {
return this.length > length ? this.substring(0, length) + "..." : this;
}
And use it like:
并像这样使用它:
var stringObject= 'this is a verrrryyyyyyyyyyyyyyyyyyyyyyyyyyyyylllooooooooooooonggggggggggggsssssssssssssttttttttttrrrrrrrrriiiiiiiiiiinnnnnnnnnnnnggggggggg';
stringObject.trimEllip(25)
回答by kendaleiv
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substr
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substr
From link:
来自链接:
string.substr(start[, length])
回答by Matthew Egan
Little late... I had to respond. This is the simplest way.
有点晚了......我不得不回应。这是最简单的方法。
// JavaScript
function fixedSize_JS(value, size) {
return value.padEnd(size).substring(0, size);
}
// JavaScript (Alt)
var fixedSize_JSAlt = function(value, size) {
return value.padEnd(size).substring(0, size);
}
// Prototype (preferred)
String.prototype.fixedSize = function(size) {
return this.padEnd(size).substring(0, size);
}
// Overloaded Prototype
function fixedSize(value, size) {
return value.fixedSize(size);
}
// usage
console.log('Old school JS -> "' + fixedSize_JS('test (30 characters)', 30) + '"');
console.log('Semi-Old school JS -> "' + fixedSize_JSAlt('test (10 characters)', 10) + '"');
console.log('Prototypes (Preferred) -> "' + 'test (25 characters)'.fixedSize(25) + '"');
console.log('Overloaded Prototype (Legacy support) -> "' + fixedSize('test (15 characters)', 15) + '"');
Step by step. .padEnd - Guarentees the length of the string
一步步。.padEnd - 保证字符串的长度
"The padEnd() method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end (right) of the current string. The source for this interactive example is stored in a GitHub repository." source: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
“padEnd() 方法用给定的字符串填充当前字符串(重复,如果需要),以便结果字符串达到给定的长度。填充是从当前字符串的末尾(右侧)应用的。此交互式的源示例存储在 GitHub 存储库中。” 来源:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/...
.substring - limits to the length you need
.substring - 限制你需要的长度
If you choose to add ellipses, append them to the output.
如果您选择添加省略号,请将它们附加到输出中。
I gave 4 examples of common JavaScript usages. I highly recommend using the String prototype with Overloading for legacy support. It makes it much easier to implement and change later.
我给出了 4 个常见的 JavaScript 用法示例。我强烈建议使用带有重载的 String 原型来获得遗留支持。它使以后实施和更改变得更加容易。
回答by MD. ABU TALHA
let trimString = function (string, length) {
return string.length > length ?
string.substring(0, length) + '...' :
string;
};
Use Case,
用例,
let string = 'How to trim a string to N chars in Javascript';
trimString(string, 20);
//How to trim a string...
回答by Babak
I think that you should use this code :-)
我认为您应该使用此代码:-)
// sample string
const param= "Hi you know anybody like pizaa";
// You can change limit parameter(up to you)
const checkTitle = (str, limit = 17) => {
var newTitle = [];
if (param.length >= limit) {
param.split(" ").reduce((acc, cur) => {
if (acc + cur.length <= limit) {
newTitle.push(cur);
}
return acc + cur.length;
}, 0);
return `${newTitle.join(" ")} ...`;
}
return param;
};
console.log(checkTitle(str));
// result : Hi you know anybody ...