Comment couper une chaîne de caractères en Javascript?

Comment puis-je, en utilisant Javascript, faire une fonction qui va couper la chaîne de caractères passée en argument, à une longueur spécifiée, également passée en argument. Par exemple:

var string = "this is a string";
var length = 6;
var trimmedString = trimFunction(length, string);

// trimmedString should be:
// "this is"

Quelqu'un a une idée? J'ai entendu parler de l'utilisation de substrats, mais je n'ai pas tout à fait compris.

99
demandé sur Lucio 2011-09-18 22:53:58

4 réponses

pourquoi ne pas simplement utiliser la soustraitance... string.substring(0, 7); le premier argument (0) est le point de départ. Le second argument (7) est le point final (exclusif). plus d'informations ici.

var string = "this is a string";
var length = 7;
var trimmedString = string.substring(0, length);
225
répondu Will 2017-08-30 08:49:45

Copie testament comment répondre à la question, parce que j'ai trouvé utile:

var string = "this is a string";
var length = 20;
var trimmedString = string.length > length ? 
                    string.substring(0, length - 3) + "..." : 
                    string;

Merci Will.

et un jsfiddle pour tous ceux qui se soucient https://jsfiddle.net/t354gw7e / :)

28
répondu Jon Lauridsen 2017-05-23 12:18:17
6
répondu kendaleiv 2011-09-18 22:19:02

je suggère d'utiliser une extension pour le code neatness

String.prototype.trim = function (length) {
  return this.length > length ? this.substring(0, length) + "..." : this;
}

et l'utiliser comme:

var stringObject= 'this is a verrrryyyyyyyyyyyyyyyyyyyyyyyyyyyyylllooooooooooooonggggggggggggsssssssssssssttttttttttrrrrrrrrriiiiiiiiiiinnnnnnnnnnnnggggggggg';
stringObject.trim(25)
6
répondu student 2018-08-23 16:46:13