Saturday 11 November 2017

How to trim a string to N chars in Javascript?

itemprop="text">

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.



itemprop="text">
class="normal">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). href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substring"
rel="noreferrer">More info
here.



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


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...