Friday, 25 August 2017

How to trim a string to N chars in Javascript?




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:



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.


Answer



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.



var string = "this is a string";
var length = 7;
var trimmedString = string.substring(0, length);

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...