I want to truncate a string after certain characters length in javascript. When the character length is reached then string should not be cut in the middle of the word rather it should complete the word and then truncate the string. What I have tried uptil now cuts the string before the cutting word. I want to include the cutting word in returned string. Here is my code:
function truncateString(yourString, maxLength) {
var trimmedString = yourString.substr(0, maxLength);
trimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")));
return trimmedString;
}
now when I call this function on with following parameters:
truncateString('The quick brown fox jumps over the lazy dog',6)
The output is 'The' rather than 'The quick.
Please point out what I need to change. Thanks
You can search for the index of immediate space after the maxLength by using the second parameter of indexOf
function truncateString(yourString, maxLength) {
// get the index of space after maxLength
const index = yourString.indexOf(" ", maxLength);
return index === -1 ? yourString : yourString.substring(0, index)
}
const str = 'The quick brown fox jumps over the lazy dog';
console.log(truncateString(str,6))
console.log(truncateString(str,10))
console.log(truncateString(str,100))
One alternative is using regex.
You can build a regex pattern based on the value passed to function.
^.{${value}}.*?\\b
| |_____________ expression to get value upto next word boundry
|
|___________________ Value passed to function
let trmStr = (input,value) => {
let reg = `^.{${value}}.*?\\b`
let regex = new RegExp(reg)
return input.match(regex)
}
console.log(trmStr('The quick brown fox jumps over the lazy dog', 6))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With