Using javascript substring() to create a read more link - javascript

I'm developing a Classic ASP page that pulls some content from a database and creates a Read more link after the first 100 characters as follows;
<div class="contentdetail"><%=StripHTML(rspropertyresults.Fields.Item("ContentDetails").Value)%></div>
<script type="text/javascript">
$(function() {
var cutoff = 200;
var text = $('div.contentdetail').text();
var rest = $('div.contentdetail').text().substring(cutoff);
if (text.length > 200) {
var period = rest.indexOf('.');
var space = rest.indexOf(' ');
cutoff += Math.max(Math.min(period, space), 0);
}
var visibleText = $('div.contentdetail').text().substring(0, cutoff);
$('div.contentdetail')
.html(visibleText + ('<span>' + rest + '</span>'))
.append('<a title="Read More" style="font-weight:bold;display: block; cursor: pointer;">Read More…</a>')
.click(function() {
$(this).find('span').toggle();
$(this).find('a:last').hide();
});
$('div.contentdetail span').hide();
});
</script>
However, the script obviously just cuts the text off after 100 characters. Preferably I would like it to keep on writing text until the first period or space, for example. Is this possible to do?
Thank you.

var cutoff = 100;
var text = $('div.contentdetail').text();
var rest = text.substring(cutoff);
if (text.length > cutoff) {
var period = rest.indexOf('.');
var space = rest.indexOf(' ');
cutoff += Math.max(Math.min(period, space), 0);
}
// Assign the rest again, because we recalculated the cutoff
rest = text.substring(cutoff);
var visibleText = $('div.contentdetail').text().substring(0, cutoff);
EDIT: shortened it a bit.
EDIT: Fixed a bug
EDIT: QoL improvement

How about:
var text= $('div.contentdetail').text();
var match= text.match( /^(.{100}([^ .]{0,20}[ .])?)(.{20,})$/ );
if (match!==null) {
var visibleText = match[1];
var textToHide = match[3];
...do replacement...
}
The {0,20} will look forward for a space or period for up to 20 characters before giving up and breaking at exactly 100 characters. This stops an extremely long word from breaking out of the length limitation. The {20,} at the end stops a match being made when it would only hide a pointlessly small amount of content.
As for the replacement code, don't do this:
.html(visibleText + ('<span>' + textToHide + '</span>'))
This is inserting plain-text into an HTML context without any escaping. If visibleText or textToHide contains any < or & characters you will be mangling them, perhaps causing a XSS security problem in the process.
Instead create the set the text() of the div and the span separately, since that's the way you read the text in the first place.

Here is a fairly simple approach to getting endings at the word level, and shooting for about your given limit in characters.
var limit = 100,
text = $('div.contentdetail').text().split(/\s+/),
word,
letter_count = 0,
trunc = '',
i = 0;
while (i < text.length && letter_count < limit) {
word = text[i++];
trunc += word+' ';
letter_count = trunc.length-1;
}
trunc = $.trim(trunc)+'...';
console.log(trunc);

Related

Removing duplicate spaces from input

<textarea id="check" cols="50" rows="20"></textarea>
<script>
var text = document.getElementById("check").value;
var lengthA = text;
for (var i = 0; i < lengthA.length; i++) {
var space = " ";
if (lengthA[i] === space) {
var next = lengthA[i] + 1;
if (next === space) {
lengthA.replace(lengthA[i], "");
}
}
}
var length3 = lengthA.length - length2;
var words = length3 + 1;
</script>
Alright bois, me got a problemo! Im attempting to make a word counter through the law that each space equals a word (1:1). Im not sure why it is not working, it makes sense to me in my mind. I have attempted several alternatives and dwelled hours upon trying to fix this chunk. Thank you in advance to anyone that answers, even if it doesn't work! :)
EDIT: Regular expressions did the trick and replaced the incorrectly used for loop and if statements. Thanks
How about just the below -
var text = document.getElementById("check").value.replace (/ +/g, " ");
Not sure, why you would need a for loop to begin with.
/ +/ will more than 1 space
g will do all the changes throughout the text
To remove the duplicate space, the following code
lengthA.replace(lengthA[i], "");
should be
lengthA = lengthA.substring(0, i) + lengthA.substring(i + 1);
// i should not increase
i--;
continue;
You misunderstand the usage of replace.
Use str.replace() of JavaScript to do this. This will remove not only space but also work for tabs, newlines etc.
Usage:
var string = string.replace(/\s\s+/g, ' ');
So change below code:
var lengthA = text;
for (var i = 0; i < lengthA.length; i++) {
var space = " ";
if (lengthA[i] === space) {
var next = lengthA[i] + 1;
if (next === space) {
lengthA.replace(lengthA[i], "");
}
}
}
To this:
var lengthA = text.replace(/\s\s+/g, ' ');
Reference here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Limit lines and characters per line in textarea (Javascript, jQuery)

What I need is to be able to limit the number of lines in a textarea. And to limit the number of characters in each line (force adding a newline when maximum number of characters has been added.
I am not interested in the "rows" and "cols" attributes. They do not work.
Also, I would like to have it working even if the user cuts or pastes something, or if he returns to a line and modifies it.
Not sure if this is an overly complex way of doing it but you can loop through the textarea and add a newline every X characters. This solution won't allow users to insert their own line breaks (it strips off any existing line breaks) .
<textarea onkeyup="formatTextArea(this)"></textarea>
<script type="text/javascript">
function formatTextArea(myArea)
{
//strip off any line breaks first
var str = myArea.value.replace(/\n|\r/g, "");
var result = '';
var i = 0
var formattedText = '';
//number of lines needed
var limit = 5
// number of characters
var limitPerLine = 20;
// loop through the text, adding a new line every limitPerLine characters
// stop after limit lines
while (str.length > 0 && i < limit)
{
i++;
formattedText += str.substring(0, limitPerLine);
str = str.substring(limitPerLine);
//only add a new line if we're not at the end of the content
if(str.length > 0 && i < limit)
{
formattedText += '\n';
}
}
myArea.value = formattedText;
}
</script>

Replace dynamically generated text elements

I am working on some code that is using dynamically generated graphs. And all of these graphs have legends at the y-axis. Now my goal is to check how long the longest legend-string is, and if the longest one is bigger than 20 characters, I only want to show the first characters of every string.
With the code below, I achieved that i can alert the desired shortened strings; but I do not know how to change the text now with these new strings.
var textLengthArray = [];
var labelStrings = domContainer.find(" g > .brm-y-direction > .tick > text");
labelStrings.each(function() {
textLengthArray.push($(this).text());
});
var longestString = textLengthArray.sort(function(a, b) {
return b.length - a.length;
})[0];
if (longestString.length >= 20) {
$("g.tick text").css("font-size", "9pt");
var offsetLeft = longestString.length * 3.7;
textLengthArray.map(function(sub) {
var subString = sub.substring(0, 6);
alert(subString);
});
};
I have tried something like:
$(labelStrings).replaceWith(subString)
With this, I had no legend at all, since I have replaced the whole text tag and all of its attributes with the new string.
So is there any way of not touching the tag and its values at all, but simply change the text between the opening and closing tag?
Thanks in advance!
sth. like this?
var $nodes = domContainer.find(" g > .brm-y-direction > .tick > text");
var longestLength = 0;
$nodes.each(function(){
longestLength = Math.max(longestLength, $(this).text().length);
});
if(longestLength >= 20){
$("g.tick text").css("font-size", "9pt");
var offsetLeft = longestLength * 3.7;
$nodes.each(function(){
var $this = $(this);
var text = $this.text();
var substr = text.substr(0, 6);
console.log(substr);
$this.text(substr);
});
}
That is basics you should research Google before coming to SO, anyway you can use $(labelStrings).html(subString) or $(labelStrings).text(subString) - they will both change only the inner content between the tags

Remove excess words from a textbox

I have a script which is almost complete but I can't figure out the last bit here. The script is meant to limit the amount of words that can be entered into a text area and if they go over the word limit these extra words are removed. I have the amount of words beyond the max labeled as overage. For instance, if you were to enter in 102 words, then the overage would be 2. How would I remove those two words from the text area?
jQuery(document).ready(function($) {
var max = 100;
$('#text').keyup(function(e) {
if (e.which < 0x20) {
return;
}
var value = $('#text').val();
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
if (wordCount == max) {
// Reached max, prevent additional.
e.preventDefault();
} else if (wordCount > max) {
<!--Edited to show code from user3003216-->
<!--Isn't working like this, textarea doesn't update.-->
var overage = wordCount - max;
var words = value.split(' ');
for(var i = 0; i<overage; i++){
words.pop();
}
}
});
});
The easiest way to approach this is just to count the number of words on keypress and go from there. Check whether there are more words than the amount allowed. If so, remove all the excess words: while (text.length > maxWords). Then just replace the value of the text box with the updated text.
fiddle
JavaScript
var maxWords = 10;
$("#myText").keypress(function (event) {
var text = $(this).val().split(" "); // grabs the text and splits it
while (text.length > maxWords) { // while more words than maxWords
event.preventDefault();
text.pop(); // remove the last word
// event.preventDefault() isn't absolutely necessary,
// it just slightly alters the typing;
// remove it to see the difference
}
$(this).val(text.join(" ")); // replace the text with the updated text
})
HTML
<p>Enter no more than 10 words:</p>
<textarea id="myText"></textarea>
CSS
textarea {
width: 300px;
height: 100px;
}
You can easily test whether it works by pasting more than maxWords—in this case, 10—words into the textarea and pressing space. All the extra words will be removed.
You can put below code into your else if statement..
else if (wordCount > max) {
var overage = wordCount - max;
var words = value.split(' ');
for(var i = 0; i<overage; i++){
words.pop();
}
}
And if you want to get your string back from that words, you can use join like below:
str = words.join(' ');
well it would be better to use java script so here you go:
var maxWords = 20;
event.rc = true;
var words = event.value.split(" ");
if (words.length>maxWords) {
app.alert("You may not enter more than " + maxWords + " words in this field.");
event.rc = false;
}
jsFiddle Demo
You can use val to re-value the text-box. The array slice method will allow you to pull the first 100 words out of the array. Then just join them with a space and stick them back in the text-box.
$(document).ready(function($) {
var max = 100;
$('#text').keyup(function(e) {
if (e.which < 0x20) {
return;
}
var value = $('#text').val();
var words = value.trim().split(/\s+/gi);
var wordCount = words.length;
if (wordCount == max) {
// Reached max, prevent additional.
e.preventDefault();
} else if (wordCount > max) {
var substring = words.slice(0, max).join(' ');
$("#text").val(substring + ' ');
}
});
});
While you've already accepted an answer I thought I might be able to offer a slightly more refined version:
function limitWords(max){
// setting the value of the textarea:
$(this).val(function(i,v){
// i: the index of the current element in the collection,
// v: the current (pre-manipulation) value of the element.
// splitting the value by sequences of white-space characters,
// turning it into an Array. Slicing that array taking the first 10 elements,
// joining these words back together with a single space between them:
return v.split(/\s+/).slice(0,10).join(' ');
});
}
$('#demo').on('keyup paste input', limitWords);
JS Fiddle demo.
References:
JavaScript:
Array.prototype.join().
Array.prototype.slice().
String.prototype.split().
jQuery:
on().
val().

jQuery ellipsis based on available space

I want to be able to ellipsis text based on how much space is available. Currently I have to provide the maximum number of characters I want to my ellipsis function but it would be far better if it did it based on available space.
How can I achieve this?
function ellipsisText(object, maxLength, ellipsistooltip) {
var grace = 3;
var text = object.text();
if (text.length - grace > maxLength) {
var etext = text.substring(0, maxLength);
etext += "...";
object.text(etext);
if (ellipsistooltip) {
object.addClass("tooltip");
object.attr("tooltiptitle", text);
}
}
}

Categories