Determine the quantity of characters available in a contenteditable field

I have implemented a directive that allows me to input editable content inside a tag

Recently, I made modifications to include a character counter feature.

However, I noticed that when I add line breaks, the character count increases erroneously.

In the image shown, the counter indicates 4 characters although visually there are only two.

In this scenario, the "<" symbol is being counted as 4 characters instead of just one, and not accounting for ">".

I am looking for an accurate way to calculate the number of characters entered.

Below is the directive code used:

directives.directive('contenteditable', ['$timeout', function($timeout) {
  return {
    restrict: 'A',
    require: ['^?ngModel'],
    link: function(scope, element, attrs, args) {
      var ngModel = args[0];
      if (ngModel === null) {
        return null;
      }
      // Code logic goes here
      // More code...
    }
  };
}]);

Answer №1

Windows considers a line feed to have 2 characters, while Linux regards it as having only 1 character. Similarly, although visually perceived as empty space, a space is actually considered a character just like the line feed.

The statement "Visually there are only two" is inaccurate because a line feed is clearly visible, making it a visual representation just like a space.

To exclude line feeds from character count, simply remove them before calculating the length. Linefeeds are represented by two characters: \r and \n, so:

var length = content.replace(/\r|\n/g, "").length;

If you wish to eliminate all line feeds, spaces, and other non-visual characters to focus solely on counting the visible characters, you can use the following:

var length = content.replace(/\s+/g, "").length;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combining two sets of elements in Java to form a Json using Jackson

Is there a way to combine two List of objects retrieved from the database into a single object in order to serialize with Jackson and deserialize in the view? ObjectMapper mapper = new ObjectMapper(); jsonTutorias = mapper.writeValueAsString(tuto ...

Is utilizing AngularJs for a Single Page Application (SPA) in a DDD project a wise decision?

Embarking on a new journey to implement an enterprise app following DDD principles. As my team and I delve into this world, we have much to learn and understand (please forgive any novice questions). The focus will be on creating a highly customized CMS. ...

Issue encountered while compiling ReactJs: Unexpected token error found in App.js

I executed the commands below. npx create-react-app github-first-app npm install --save react-tabs npm i styled-components npm install git-state --save using the following code files App.js import React from "react"; import Layout from " ...

Fading text that gradually vanishes depending on the viewport width... with ellipses!

I currently have a two-item unordered list positioned absolutely to the top right of the viewport. <header id="top-bar"> <ul> <li> <a href="#">David Bowie</a> </li> <li> ...

Is it feasible to evaluate a Typescript method parameter decorator at request time in a nodejs+nestjs environment rather than just at build time?

Looking to simplify my handling of mongodb calls with and without transactions in a single service method by writing a decorator. This would help eliminate the repetition of code and make things more efficient. Key points for usage: • Service class has ...

How come React-Native isn't displaying successfully retrieved data using Axios?

I recently installed axios using the command below: npm i axios After writing the code below, I encountered an issue where React-Native doesn't display any data or throw any errors: import React, {useState, useEffect} from 'react'; import a ...

Persistent hover state remains on buttons following a click event

In my current project, I am dealing with a form that has two distinct states: editing and visible. When the user clicks on an icon to edit the form, two buttons appear at the bottom - one for saving changes and one for canceling. Upon clicking either of th ...

By pressing the "showMore" button, the page dynamically pulls in a json list from a file

Currently, my focus is on a dropwizard-Java project. My task involves retrieving and showcasing the first 10 items from a json list in a mustache view. If the user clicks on the "show more" link, I should retrieve the next 10 elements from the list and d ...

Exploring the functionality of placeholders within jQuery

I am trying to create a customizable text template where I can insert placeholders and then fill those placeholders with data to use on my page. For example: var template = '<div class="persons">'; template += '<p> <span clas ...

Preventing AngularJS from Ignoring HTML Elements

Is there a way to calculate HTML content within an AngularJS object (such as {{names}}) that includes an '<a>' element? When I try to display it, the result looks like this: <a href="http://www.example.com">link text</a> I&ap ...

What is the best way to determine and showcase the hours that have passed since the user's initial visit to the website?

Can someone provide guidance on how to finalize the hoursSinceFirstVisit() function implementation? Additionally, what content should be displayed on my HTML page? $(document).ready(function() { startTimer(); }); function startTimer() { setInte ...

Expand and enhance your content with the Vue Sidebar Menu plugin

Recently, I integrated a side-bar-menu utilizing . My goal is to have a sidebar menu that pushes its content when it expands. Any suggestions on which props or styles I should incorporate to achieve this effect? Below is my Vue code: <template> ...

Is there a way to change the data type of all parameters in a function to a specific type?

I recently created a clamp function to restrict values within a specified range. (I'm sure most of you are familiar with what a clamp function does) Here is the function I came up with (using TS) function clamp(value: number, min: number, max: number ...

Steps to eliminate the select all checkbox from mui data grid header

Is there a way to remove the Select All checkbox that appears at the top of the checkbox data column in my table? checkboxSelection The checkboxSelection feature adds checkboxes for every row, including the Select All checkbox in the header. How can I ...

What is the method to show text on hover in angularjs?

I'm a beginner in AngularJS and I'm looking to show {{Project.inrtcvalue}} when the mouse hovers over values. Can anyone guide me on how to achieve this using AngularJS? <table ng-table="tableParams" show-filter="true" class="table" > ...

Error occurs in console when using .getJSON with undefined JSON, but does not happen when using embedded data

Can someone help me understand why I'm getting an 'undefined' response when I use console.log(tooltipValues), but there's no issue with console.log(tooltipJSON). I've noticed that when I embed the data directly in my JS code, ever ...

Utilizing JavaScript to retrieve data from a self-submitting form

From my database, I am able to create a list of options for users to choose from. Once a selection is made, the values are submitted back to the same page and retrieved using Javascript. Within the same form, there are radio buttons and a multiple selecti ...

What is the best way to include a JavaScript variable in an HTML image src tag?

Even though I know the answer to this question is out there somewhere, I just can't seem to find it (or maybe I'm not recognizing it when I see it!). As a beginner in jquery, please be patient with me. Dilemma: I have a collection of 20 images, ...

Utilizing Highcharts/Highstock for handling large volumes of data efficiently

Dealing with a growing amount of data daily (currently over 200k MySQL rows in one week), the chart loading speed has become quite slow. It seems like using async loading is the solution (). I attempted to implement it but encountered some issues. Currentl ...

Is there a method to use media queries to dynamically switch JavaScript files based on the user's device?

I've been working on optimizing the mobile layout of my website, and while I have successfully implemented a media query with a different stylesheet for mobile devices, I'm struggling to determine if it's feasible to also load a separate Jav ...