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
x
7
1
var string = "this is a string";
2
var length = 6;
3
var trimmedString = trimFunction(length, string);
4
5
// trimmedString should be:
6
// "this is"
7
Anyone got ideas? I’ve heard something about using substring, but didn’t quite understand.
Advertisement
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.
JavaScript
1
4
1
var string = "this is a string";
2
var length = 7;
3
var trimmedString = string.substring(0, length);
4