Tuesday, 22 September 2015

Truncate strings in Javascript

Truncate strings with javascript

Javascript doesn't have an inbuilt function for truncating string(I haven't seen one).
When i say truncate i mean something like shorten. E.g the sentence "David was a mighty King" could be truncated to "David was a..."
I hope you get the gist now

So we would make a function we name trunc. It will actually be a String prototype. The trunc function will be used as follows:

//The string

var str="Examples of fruits are: apple, mango, orange, coconut, banana,cashew and cherry. God made them all."

//trunc to the rescue!

document.write(str.trunc(44))

The result will be:

It returns only the first 44 words and append '...' to it.
Okay! So here's the simple function. This is accomplished using substring. Use can also use substr.

The function:

String.prototype.trunc=function(x){
return ""+this.substr(0,x)+"...";
}
And the use:
var str="Examples of fruits are: apple, mango, orange, coconut, banana,cashew and cherry.
God made them all."
alert(str.trunc(44))
//alerts: Examples of fruits are: apple, mango, orange...

Thanks and God bless.



No comments:

Post a Comment