Method One: Set the length. So that after the 10th character, if any space appears the string will get truncated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
var setLength=10; function truncateString(string, limit, breakChar, rightPad) { if (string.length <= limit) return string; var substr = string.substr(0, limit); if ((breakPoint = substr.lastIndexOf(breakChar)) >= 0) { if (breakPoint < string.length -1) { return string.substr(0, breakPoint) + rightPad; } } } var text = 'Break this string once the character count reaches to specified length in setLength variable.'; console.log(truncateString(text, setLength, ' ', '...')); |
Output:
Method two:
|
var yourString = "Break this string once the character count reaches to specified length in setLength variable."; //replace with your string. var maxLength = 6 // maximum number of characters to extract //trim the string to the maximum length var trimmedString = yourString.substr(0, maxLength); //re-trim if we are in the middle of a word trimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" "))) |
Output:
Method three: Using regular expresion
|
var string = "Javascript regular expresion to shorten string without cutting words"; document.write("1: " + string.replace(/^(.{1}[^\s]*).*/, "$1") + "\n"); document.write("2: " + string.replace(/^(.{2}[^\s]*).*/, "$1") + "\n"); document.write("5: " + string.replace(/^(.{5}[^\s]*).*/, "$1") + "\n"); document.write("11: " + string.replace(/^(.{11}[^\s]*).*/, "$1") + "\n"); document.write("20: " + string.replace(/^(.{20}[^\s]*).*/, "$1") + "\n"); document.write("100: " + string.replace(/^(.{100}[^\s]*).*/, "$1") + "\n"); |
Output:
|
1: Javascript 2: Javascript 5: Javascript 11: Javascript regular 20: Javascript regular expresion 100: Javascript regular expresion to shorten string without cutting words |
Likes(0)Dislikes(0) Please rate this Sample rating item
