The regex expression (/[\n\r]/gm) fails to detect double line breaks in a textarea using Javascript

If you want to check out my work on GitHub, feel free to view the code here:

The JavaScript is triggered by keydown and will create something.

I organize the output by paragraph (new line), with JS removing newlines from arrays using Regex (/[\n\r]/gm).

However, if I add more than 2 empty lines before continuing typing, the regex doesn't detect it.

Example of textarea input:

PO PO PO PO
<--This part detected as newline-->
PO
<--This part detected as newline-->
<--This part unable to detect as newline-->
PO

Result in Console.log:

["po po po po", "po", "", "po"]


My Code for getting textarea value and creating an array:

var crinput = document.getElementById("textarea1").value
var paracountarray = crinput.split(/[\n\r]/gm);

My code for removing empty strings in the array:

for(a=0;a<paracountarray.length;a++){
        if(paracountarray[a] == ""){
            paracountarray.splice(a,1)
        }
    }

Please let me know how to remove the empty strings in the array.

Answer №1

It seems like there might be some confusion without a functional JSFiddle example to reference. When I run your code in the console, it produces an extra empty array element:

>> var testStr = 'PO PO PO PO\n\nPO\n\n\nPO'
>> testStr.split(/[\n\r]/gm)
Array [ "PO PO PO PO", "", "PO", "", "", "PO" ]

If you are aiming for a different outcome, you could try using a "once or more times" match like this:

var paracountarray = crinput.split(/[\n\r]+/gm);

This would treat fifteen consecutive newlines as a single paragraph break, resulting in three paragraphs in the given example. Compare it with the previous method:

>> var testStr = 'PO PO PO PO\n\nPO\n\n\nPO'
>> testStr.split(/[\n\r]+/gm)
Array [ "PO PO PO PO", "PO", "PO" ]

Answer №2

To detect multiple line breaks simultaneously, you can utilize the following regular expression: /[\r\n]+/gm.

function countLines(){
  var textInput = document.getElementById("textarea1").value
  var linesArray = textInput.split(/[\r\n]+/gm);
  console.log(linesArray);
}
<textarea id="textarea1" onchange="countLines()"></textarea>

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

Accessing JSON Data Using JQUERY

Currently, I am experimenting with grabbing JSON data from websites using the $.getJSON() method. Here is the code snippet I have been working on: The website I am attempting to retrieve JSON data from can be found here. Interestingly, the code functions ...

Issue with inserting ContentPlaceHolder in script tags

In my ASP.Net Master Page, I encountered an issue: <script language="javascript" type="text/javascript"> <asp:ContentPlaceHolder ID="scriptContentHolder" runat="server"></asp:ContentPlaceHolder> </script> When attempt ...

Ajax is bypassing the success:function callback

Currently, I am working on implementing a login feature using ajax, HTML, and PHP. After debugging the PHP code, everything seems fine as it returns the necessary JSON variable for the ajax call. Below is the AJAX function I have created: $(document).read ...

Issue with the alphabetical ordering of subpages

My PageSidebar.js component lists child pages alphabetically. https://i.sstatic.net/DZro1.png However, when I navigate to a child page, the alphabetical order is not maintained. https://i.sstatic.net/fRVgO.png I've tried multiple solutions but hav ...

difficulties with utilizing the Java toLowerCase method with arrays and numerous 'terms' in the provided string

My knowledge of Java is very limited, to the point where I struggle to write even 20 lines of basic code that actually work. Currently, I am facing two issues with my code which may or may not be related, as they stem from similar pieces of code that I hav ...

Is it possible to manipulate a modal within a controller by utilizing a certain attribute in HTML, based on specific conditions (without relying on any bootstrap services), using AngularJS?

Within my application, I have a modal that is triggered by clicking on a button (ng-click) based on certain conditions. Here is the HTML code: <button type="button" class="btn btn-outlined" ng-click="vm.change()" data-modal-target="#add-save-all-alert ...

Activate event in jQuery when clicking on a blank area, away from any div element

I need help figuring out how to hide a div when empty space on the margins of the page is clicked, as opposed to just any area outside of the div. I've managed to achieve this functionality when certain other divs are clicked, but I'm stuck on im ...

"Error: ArrayIndexOutOfBoundsException occurred, even though the array size was correctly

Encountered an error in my program output that abruptly ended the process. Only 8 student objects were displayed. Here is a snippet of the output where the error occurred: ******************************************************************** ************** ...

Weaknesses found in the React Js library bundled with create-react-app

Each time I initiate a new react project using npx create-react-app <AppName>, the following vulnerabilities are detected: 96 vulnerabilities found - Packages audited: 1682 Severity: 65 Moderate | 30 High | 1 Critical Node Version: v14.18.1 Npm: 7.20 ...

AngularJS users are experiencing issues with the "See More" feature not functioning as expected

One of my tasks involves dealing with a block of text that needs to be truncated using ellipsis. To achieve this, I am utilizing jquery dotdotdot. For more information on dotdotdot, please refer to the documentation. I have created a straightforward dire ...

update the status of the isChecked checkbox in the parent element

Family component class Family extends Component { constructor(props) { super(props); this.state = { checkedMembers:[ {id: 1, name: "Alice", isChecked: false}, {id: 2, name: "Bob", ...

Experiencing difficulty with writing Array values to memory

I'm currently working with an Arduino along with an Adafruit FRAM memory breakout board. My goal is to retrieve values from an array and then store them in the FRAM. However, I am facing an issue where the saved values are not correct. What kind of co ...

What is the module system that fabric composer utilizes for its logic JavaScript files?

I am currently in the process of creating a business-network-definition for Hyperledger using Fabric (based on generator-hyperledger-fabric). Everything has been running smoothly so far, but as we move onto our Proof of Concept (PoC), a few questions have ...

MUI-Datatable: Is there a way to show the total sum of all the values in a column at once

I have a column displaying the Total Amount, and I am looking for a way to show this totalAmount. After conducting some research, it seems like onTableChange is the key. Currently, it effectively displays all of the data using console.log("handleTab ...

The Electron forge project from publisher-github is failing to detect the environment variable GITHUB-TOKEN

I've set up my .env file with the correct token, but I encountered an error when trying to publish my package on GitHub. An unhandled rejection has occurred inside Forge: Error: Please set GITHUB_TOKEN in your environment to access these features at n ...

Comparing data in two arrays with Matlab to find and output the largest value

I am working with a 60,000-by-2 array where the first column represents data 1 and the second column represents data 2, both being of equal length. I am struggling to figure out the correct syntax for comparing data 1 to data 2, and then writing the resu ...

The alert function is not being triggered upon receiving a JSON response

I am having trouble with an alert not firing a json response. The response appears in firebug, but after upgrading from php4.4.7 to php5.3.5, I encountered this error. It could be my mistake as well. Could someone please review my code and point out where ...

Ways to adjust the position of a DIV based on its index value

I'm currently working on a unique project that involves creating a triangular grid using HTML and CSS. The challenge I am facing is offsetting each triangle in the grid to the left by increasing amounts so they fit seamlessly next to one another. Righ ...

Issues with Google API Column chart example in jsfiddle demonstration are hindering its functionality

I'm attempting to make the Google Column Chart example provided here function properly. Here is my effort: http://jsfiddle.net/dwNE4/ (Note: I'm having some difficulty getting it to load) This is the code from the fiddle: HTML <script src=&q ...

What is the process for removing a row from the database in this scenario?

My current goal is to implement a functionality where clicking on the "Delete" button will remove a file from the server and also delete the corresponding database entry with the same file name. The file deletion process on the server works perfectly, but ...