A JavaScript regex that can identify white spaces and new lines to calculate word count

Currently, I am attempting to count words within the Summernote editor using Angular. While I have successfully created a service for counting words, it seems to be ineffective when encountering new lines.

Here is an example of the text:

Hult International 23

s

e

r

t

My attempt at solving this issue has been as follows:

if (text && text.length > 0) {
    text = text.replace(/<(?:.|\n)*?>/gm, '').replace(/&amp;nbsp;/g, '').replace(/&nbsp;/g, '').trim();
    return text.length ? text.split(/\s+/).length : 0;
}

You can also view the problem in the image linked here.

Answer №2

By replacing \n with nothing, you eliminate all spaces between lines and combine the letters in 23sert into a single word. I'm not entirely clear on the purpose of the replace action, but if your text doesn't contain non-word symbols, you could simply use

return text && text.length ? text.split(/\s+/gm).length : 0
instead of the entire block you have.

(May require some adjustments to handle leading/trailing spaces)

Answer №3

After conducting a thorough investigation into the structure of regex, I successfully replaced white spaces when replacing tags.

text = text.replace(/<(?:.|\n)*?>/gm, ' ').replace(/&amp;nbsp;/g, '').replace(/&nbsp;/g, '').trim();

I'm sharing this answer in hopes that it may help someone else.

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

Encountered an unexpected symbol < in JSON while implementing fetch() operation

I'm currently working on linking my React signup page to my Django API in order to automatically create a user profile in Django when a user signs up. Whenever I attempt to create a new user, I encounter this error in my console: Signup.js:33 ...

Is there a way to eliminate the feature that rearranges characters in reverse order?

Is there a way to modify this code to only replace vowels with "er" instead of reversing the order of characters? I'm hoping to remove the function that reverses the character order. If you want to take a look at the code, it's available on Past ...

My React/Redux App is experiencing difficulties as the state fails to load

Currently, I am working on a project based on the Redux Documentation page. Instead of uploading it directly to Stack Overflow, I decided to share my progress on GitHub: https://github.com/davidreke/reduxDocumentationProject I have completed the instructi ...

What sets apart a React component from a function-as-component in React?

React is really confusing to me right now. Take this simple react component for example: export default function Foo(){ return( <div> <div>some text</div> </div> ) } I want to add a child compone ...

Retrieving information from an API and presenting it as a name with a link to the website

I am attempting to retrieve information from an API and present it in the format Name + clickable website link. Although I have managed to display the data, the link appears as text instead of a hyperlink. Here is my Ajax script: $(function() { ...

Is the state of the React.js component empty?

HTML: <!-- index.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>React Tutorial</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script> ...

Can you explain the significance of this specific form of variable declaration?

Have you ever been in a situation where you receive some code that actually works, but you're not sure how it's working? For example, what exactly does this declaration method accomplish? const { actions: { createRole, updateRole } = {} } = prop ...

End the div element upon completion of the Vimeo video

I am in need of a website that includes an intro video displayed as a full-width div over the background content. To achieve this, I created a Div containing an iframe video from Vimeo along with a button to skip the intro (which closes the div upon clicki ...

Warning: Unhandled promise rejection detected

I'm encountering an issue with Promise.reject A warning message pops up: Unhandled promise rejection warning - version 1.1 is not released How should I go about resolving this warning? Your assistance is greatly appreciated public async retrieveVe ...

What is the best way to combine a JSON response object with the variable J inside a for loop?

Received a JSON response as follows: { "name" : "chanchal", "login3" : "1534165718", "login7" : "1534168971", "login6" : "1534168506", "login5" : "1534166215", "login9" : "1534170027", "login2" : "1534148039", "lastname" : "khandelwal", ...

Transform all the string data to integers in the JSON reply

Apologies for the basic question: This is the response I'm receiving: {id: "bitcoin", name: "Bitcoin", symbol: "BTC", rank: "1", price_usd: "15487.0"} I want to convert rank: "1", price_usd: "15487.0" to rank: 1, price_usd: 15487.0 The reason beh ...

Encountering a hiccup during the installation process of Angular CLI

I'm encountering an issue in the command line, seeking assistance C:\Users\admin>npm -v 6.9.0 C:\Users\admin>npm install -g @angular/cli npm ERR! Unexpected end of JSON input while parsing near '...vkit/core":"8.0.4", ...

Failure to give an error message occurred during a POST request on Parse.com and ExpressJS platform

I'm facing an issue where a POST request I send fails with error code 500 and there is nothing showing up in my server side error log. It seems like the cloud method may be missing. What's interesting is that the same POST request works fine wit ...

What is the process for uploading files with just node.js?

My dilemma involves a webpage featuring a form with a file input field. Upon submitting the form, I wish for the server to write the file on the server side. Despite numerous attempts to upload various test images using this form, each results in a plain ...

Discover the best practices for utilizing the npm commands.test function

Looking to create a function that can return the output from running npm test. (this function can be called as npm.commands.test(packages, callback) here) Attempted to use it in this way: var npm = require("npm"); npm.load('', function(err, np ...

transferring data from HTML to JavaScript functions

I am facing an issue with my ng-repeat in the view where I want to pass the object from the ng-repeat to a javascript function. However, when I attempt to display it on the console, it shows up as undefined. Below is the HTML code snippet: <!-- Panel ...

Is it possible to dynamically insert one module into another module?

Let's say I have 2 modules in two separate files: The first one is for everyone, let's call it myApp: var myApp = angular.module('myApp', ['dependency.one', 'dependency.one']); In another file named admin.js, I ha ...

Strive to discover the ideal solution for capturing a screenshot of an OpenLayers map using html2canvas. Currently, the map elements are losing their CSS classes and images are not

Seeking advice on the best solution for working with html2canvas and css. I'm trying to take a screenshot of a map that includes various elements, but after capturing the image, all the css classes are lost and the images are not rendered properly. S ...

Stop the change event from occurring on a textarea when the user clicks on an external cancel button

In a particular scenario, there is a textarea with an autosave feature triggered by the change event. When the textarea is focused on, Save and Cancel buttons appear at the bottom, providing users with options in case they prefer not to simply click outsid ...

Utilize AJAX, jQuery, and Symfony2 to showcase array information in a visually appealing table format

I have a requirement to showcase data utilizing ajax and jQuery in a table on my twig file. The ajax call is made with a post request to the controller, where the controller attempts to input several rows from a csv file into the database. However, there ...