How to cut off last 20 characters from a normal html paragraph with a classname which contains two words? For instance <p class="sentence slice">Last twenty characters have to be chopped off!!!</p>
I know there's a slice method in JS https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice but how to implement this onto the website?
If you are interested in using .slice, all you need to do is this:
JavaScript
$("#clickme").click(function () {
var text = $("p").text();
text = (text.length > 20) ? text.slice(0,-20) : text;
// important to check whether the text is longer than 20 characters
$("p").text(text); // update the text
})
HTML
<p>Lots and lots and lots and lots and lots of text12345678901234567890</p>
<button id="clickme">remove last 20 characters</button>
fiddle
You can do:
$("p.sentence.slice").text(function() {
var text = $(this).text(),
length = text.length;
if (length > 20)
return text.substr(0, (length - 20));
else return text;
});
Since you are mentioning the following, let's assume that you don't know the actual name of the classes; you just know that the paragraph tag that you want to modify, definitely contains two classes.
(...) with a classname which contains two words?
Using tymeJV's solution (using substr), the following will only modify a paragraph tag which contains exactly two classes, and its length (in characters) is greater than 20.
$('p').each(function () {
var classes = $.trim($(this).attr('class'));
var count = classes.split(' ');
var text = $(this).text();
if(count.length === 2 && text.length > 20) {
$(this).text(text.substr(0, (text.length - 20)));
}
});
Demo: http://jsfiddle.net/EP47z/
Related
I am working on a browser extension (a content script) where I want to process all the text on a webpage and replace some of the text without breaking the webpage.
I filter relevant nodes using createTreeWalker then I iterate over them:
let nodes = document.createTreeWalker(...);
while ((node = nodes.nextNode())) {
let text = node.nodeValue;
...
}
The problem I have is that for a span like
<span class="a-text-bold">Product
:
</span>
node.nodeValue returns a string like
"Product
:
"
When I modify the dom and replace the node with a new one, I break the formatting since I don't have the HTML entities and .
How can I retrieve the actual content of the span
"Product
:
"
?
Entities just encode characters (in this case, the characters U+200F and U+200E). Provided you don't replace them when replacing other things in the string, the marks will still be there once you finish the replacement. For instance, here are the code points of the characters in _:
const text = document.getElementById("x").childNodes[0].nodeValue;
console.log(
Array.from(text, (ch) => `0x${ch.codePointAt(0).toString(16).toUpperCase()}`).join(" ")
);
<div id="x">_</div>
As you can see, the marks are there.
The / in your example doesn't seem to do anything, but using some text from Wikipedia, here's an example of updating nodeValue and how it doesn't strip away the or :
const elements = document.querySelectorAll(".a-text-bold");
let counter = 0;
setInterval(() => {
for (const element of elements) {
const textNode = element.childNodes[0];
const from = counter % 2 === 0 ? "enjoyed" : "loved";
const to = counter % 2 === 0 ? "loved" : "enjoyed";
textNode.nodeValue = textNode.nodeValue.replace(from, to);
}
++counter;
}, 1000);
<p class="a-text-bold">I enjoyed staying -- באמת! -- at his house.</p>
<p>For comparison, here's that text <strong>without</strong> the ‏ =></p>
<p class="a-text-bold">I enjoyed staying -- באמת! -- at his house.</p>
<p>Notice how the ! appears before (rather than after) the hebrew text when the ‏ is present, and that it still does after the replacement has been done.</p>
I have a column named DESC in mysql database. I set it to Varchar(255) latin-1.
Before storing data in mysql database i use
filter_var(mysqli_real_escape_string($value),FILTER_SANITIZE_SPECIAL_CHARS)
My question is how do I implement jquery character counting and maxlength restriction and be able to retrieve & display all the data from the textarea?
My Pseudo code
// Set MaxLength to 255
max= 255;
// Get length of textarea
$(this).val().length
// Count how many &, <,>,",' then multiply by 4 (as each of these characters will convert into &#??? which add extra 4 characters into database) and Newline (add extra 1 character) in the textarea.
CountSpecial($(this).val()); //bug #1
// calculate remaining characters.
Remaining = max - $(this).val().length -CountSpecial($(this).val());
//Limit the data to varchar(255) to avoid data truncation.
If (Remaining <0) {
//truncate to fix varchar(255)
$(this).val($this.val().substring(0,$this.val().length+Remaining); //bug#2
//recalculate Remaining.
Remaining = max - $(this).val().length -CountSpecial($(this).val());
}
Bug #1, I dont know how to accurately calculate the extra characters will be stored into database
Bug #2 I tried
$(this).val($this.val().substring(0,$this.val().length-1);
but it doesn't behave the way I want, as I use keyup function, if the user keeps holding a key, this calculation will not work.
$(this).val($this.val().substring(0,$this.val().length+Remaining);
fixed the problem when the user keeps holding a key, but product another problem. If the user key in something like "&" it will remove the last 4 characters from textarea not 1.
Here is my original code
http://jsfiddle.net/seth1111/orLh4v4w/5/
How do i fix these bugs?
Thanks.
You can create a jQuery Remaining character counter by this simple code.
$(function() {
$(document).on('keyup paste', '#address', function (e) {
var value = $(this).val();
var limit = 10; // Max character you want to allow
var length = value.length;
var remaining = parseInt(limit - length);
$('#result').html(remaining+' Character(s) Remaining');
if(length < limit)
{
$('#result').show();
$('#error').hide().removeClass('error').html('');
}
else if(length > limit)
{
$('#result').hide();
this.value = this.value.substring(0, limit);
$('#error').show().addClass('error').html('Maximum ' + limit + ' Characters are allowed!');
}
});
});
HTML part is
Enter Address: <textarea cols="21" rows="5" name="address" id="address"></textarea>
<p id="result"></p>
<p id="error" style="display: none;"></p>
CSS for error class
.error {
color:#f00 !important;
}
Just this simple code will done your task.
If you still need help feel free to comment.
You can simply check special characters and new lines with the String.match function in javascript.
realLength = $(this).val().length;
specialCarLength = $(this).val().match(/[&"',<>]/g);
specialCarLength = specialCarLength === null ? 0 : specialCarLength.length * 4;
NewLineCarLength = $(this).val().match(/\n/g);
NewLineCarLength = NewLineCarLength === null ? 0 : NewLineCarLength.length * 2;
NormalCarLength = realLength-specialCarLength/4-NewLineCarLength/2;
check my jsFiddle, it demonstrate how you can match special characters and new lines : jsFiddle
Say I have the following HTML:
<div>Some text</div>
I'm wanting to remove the last character from the text each time the user hits the backspace key. Is there a way to actually remove a character from a text node? Or do I have to do something like obj.innerText = 'Some tex' (i.e. trim the last char myself and replace the whole thing).
var div = document.getElementById('my-div');
document.addEventListener('keydown',
function(e) {
if (e.which === 8) {
div.textContent = div.textContent.substring(0, div.textContent.length - 1);
}
}, false);
You may also want to support IE8. In that case, use document.attachEvent() and div.innerText.
Best method I can think of off the top of my head is to use the substring method for Strings.
var s = obj.innerText
// Then On backspace event listener
s = s.substring(0, s.length - 1) // returns s without the last character in the original string.
obj.innerTezt(s) // set the inner HTML back to s
Edit: thanks Jonathan, Dennis for the correction on this answer!
// Get the element
var el = document.queryString("...")
// Get the text contents
var text = el.firstChild
if (text.nodeType === Node.TEXT_NODE) {
// Delete the last character
text.deleteData(text.length - 1, 1)
}
See the CharacterData DOM interface for details of deleteData
I count the words in a contenteditable. I split it using spaces. The problem comes when you enter a new line. It doesn’t count the word you’re currently writing on the new line until you add a space.
On top of that, in the following example if you split the example text into two lines, it will “eat up” one word when you do that:
http://jsfiddle.net/MrbUK/
I’m guessing this issue exists because between HTML elements there are no spaces:
<div>some things</div><div>are cool</div> its string would be “some thingsare cool”.
Here’s the code that I have:
function wordCount() {
var content_text = $('#post_content').text(),
char_count = content_text.length,
word_count = 0;
// if no characters, words = 0
if (char_count != 0)
word_count = content_text.replace(/[^\w ]/g, "").split(/\s+/).length;
$('.word_count').html(word_count + " words • " + char_count + " characters");
}
I tried replacing some HTML tags:
word_count = content_text.replace(/ /g, " ").replace(/<div>/g, "<p>").replace(/<\/div>/g, "</p>").replace(/<\/p><p>/g, " ").split(/\s+/).length;
without any luck. I need to discard whether it’s a <p> or <div> and some browsers add when merging lines together.
Any ideas? Thanks!
EDIT:
Thanks to Jefferson below for his clever method, I managed to solve this. For some reason I have to do -1 on the word_count to display the correct number of words:
function wordCount() {
var content_div = $('#post_content'),
content_text,
char_count = content_div.text().length,
word_count = 0;
// if no characters, words = 0
if (char_count != 0)
content_div.children().each(function(index, el) {
content_text += $(el).text()+"\n";
});
// if there is content, splits the text at spaces (else displays 0 words)
if (typeof content_text !== "undefined")
word_count = content_text.split(/\s+/).length - 1;
$('.word_count').html(word_count + " words • " + char_count + " characters");
}
You can use this:
$("#post_content").children().each(function(index, el){buffer += $(el).text()+"\n"})
This way you iterate by all elements inside your div and get only the text, put a "\n" between them.
Jefferson's answer was great, and it helped me with this exact same issue.
The problem I encountered was the contents of my contenteditable div was not entirely wrapped in HTML tags.
For example, my div contained the following HTML code:
This is my first line<div>This is my second line</div>
By using $.children(), it was ignoring the first line and only returning a word count of 5. To get round this I used $.contents() instead. Modified code is below:
$("#post_content").contents().each(function(index, el){buffer += $(el).text()+"\n"})
This returned a line count of 10.
Apologies for adding this as an answer and not as a comment to Jefferson's answer, however my reputation is too low to allow me to do that. I felt it was worth pointing the above out though.
I have seen plenty of code snippets to force a <Textarea> to have only X number of characters and then not allow anymore. What I am in need of is a <Textarea> where you can specify how many characters I can have at one time at most. Almost like a max buffer size. Think of it like a rolling log file. I want to always show the last/newest X number of characters.
Simpler the solution the better. I am not a web expert so the more complicated it gets the more greek it looks to me. :)
I am already using jQuery so a solution with that should be ok.
try this:
<textarea id="yourTextArea" data-maxchars="1000"></textarea>
var textarea = document.getElementById('yourTextArea');
var taChanged = function(e){
var ta = e.target;
var maxChars = ta.getAttribute('data-maxchars');
if(ta.value.length > maxChars){
ta.value = ta.value.substr(0,maxChars);
}
}
textarea.addEventListener('change', taChanged, 1);
for the last chars:
ta.value = ta.value.substr(ta.value.length - 1000);
And jQuery implementation:
$('#text').keyup(function() {
var max = $(this).data('maxchars'),
len = $(this).val().length;
len > max && $(this).val(function() {
return $(this).val().substr(len - max);
});
});
http://jsfiddle.net/WsnSk/
No code, I can't even spell JavaScript, but basically as you're about to add new text, check the length of the existing text. If the old text plus the new text is too long, trim off the beginning of the old text (likely at a newline or whatever). Rinse and repeat.
Here is the working code on Fiddle. It uses Jquery to make it simple.
<textarea id="txtArea"></textarea>
var size = 5;
$('#txtArea').change(function(){
var strValue = $('#txtArea').val();
strValue = strValue.split("").reverse().join("").substring(0, size).split("").reverse().join("");
alert(strValue);
});