Thursday, July 4, 2019

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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...