Shorten string without cutting words in JavaScript
If I understand correctly, you want to shorten a string to a certain length (e.g. shorten "The quick brown fox jumps over the lazy dog"
to, say, 6 characters without cutting off any word).
If this is the case, you can try something like the following:
var yourString = "The quick brown fox jumps over the lazy dog"; //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(" ")))
There are lots of ways to do it, but a regular expression is a useful one line method:
"this is a longish string of text".replace(/^(.{11}[^\s]*).*/, "$1");
//"this is a longish"
This expressions returns the first 11 (any) characters plus any subsequent non-space characters.
Example script:
<pre>
<script>
var t = "this is a longish string of text";
document.write("1: " + t.replace(/^(.{1}[^\s]*).*/, "$1") + "\n");
document.write("2: " + t.replace(/^(.{2}[^\s]*).*/, "$1") + "\n");
document.write("5: " + t.replace(/^(.{5}[^\s]*).*/, "$1") + "\n");
document.write("11: " + t.replace(/^(.{11}[^\s]*).*/, "$1") + "\n");
document.write("20: " + t.replace(/^(.{20}[^\s]*).*/, "$1") + "\n");
document.write("100: " + t.replace(/^(.{100}[^\s]*).*/, "$1") + "\n");
</script>
Output:
1: this
2: this
5: this is
11: this is a longish
20: this is a longish string
100: this is a longish string of text