Adding word counter using javascript

By: Nikita Dobaria | Asked: 10/22/2022
ForumsCategory: Code HelpAdding word counter using javascript
Nikita Dobaria asked 2 years ago
Hi, I want to add word counter below text area. For this I got javascript on formidable forms knowledge-base. Below is the link and code. Link - Code - jQuery(document).ready(function($){
var s = this.value;
s = s.replace(/(^s*)|(s*$)/gi,"");
s = s.replace(/[ ]{2,}/gi," ");
s = s.replace(/n /,"n");
document.getElementById("frm_field_400_container").innerHTML = (s.split(' ').length) + ' words';
}); Above code is only able to count words when written in continuation giving spaces, but it is not able to count numbers when each word starts with a new line. Can someone provide JavaScript code for word counter for count words starting from the new line. Please Note - I do not have coding knowledge. Thanks
1 Answers
Rob LeVineRob LeVine answered 2 years ago
It appears that code sample doesn't handle newlines, even though it looks like it tries to. Try the following, replacing the field KEY associated with the keyup function (after "#field_") and the field ID in the innerHTML statement (after "frm_field_") String.prototype.countWords = function(){ return this.split(/\s+\b/).length; } jQuery(document).ready(function($){ $('#field_typehereparagraph').keyup(function(){ var s = this.value; var numWords = s.countWords(); document.getElementById("frm_field_438_container").innerHTML = numWords + ' words'; }); });
Rob LeVineRob LeVine replied 2 years ago

Sorry for the formatting, but I have yet to figure out how to correctly use the "code" blocks in these answers. Every once in a while I accidentally get it right.

Bobby Clapp replied 1 year ago, then paste the link created. It's ugly here.

Rob LeVineRob LeVine replied 1 year ago

Good point! I forget about that option approximately 100% of the time.

Rob LeVineRob LeVine replied 1 year ago

Here is nicely formatted code -

Making the Best WordPress Plugin even better - Together

Take on bigger projects with confidence knowing you have access to an entire community of Formidable Experts and Professionals who have your back when the going gets tough. You got this!
Join the community