Using Regex instead of the method resulted in logging an unexpected output, displaying the matched text as $& and the

I have a regular expression that I'm using with the .replace method to extract paragraphs from a string and add them to an array.

I've been struggling with my getValues function; when I logged Match and Group1 to the console, I got unexpected results.

Here's the work in progress code:

var mystring = 'Valid prater\nLorem ipsum dolor sit amet, consectetur adipiscing elit. \nProin volutpat facilisis imperdiet. \n Nunc porttito\nMorbi non eros nec arcu condimentum ultrices in ut nunc. \nMaecenas elit tellus, scelerisque ac auctor fermentum, bibendum. '

var paragraphs = [];
var obj = {};

var getValues = function(match,p1) { 
  console.log('Match: ' + match );
  console.log('p1: ' + p1 );

    // obj= {};
    // obj['paragraph'] = p1; 
    // paragraphs.push(obj);
 };

mystring.replace(/([^\\n][^\\]+)/g, getValues);

https://jsfiddle.net/7293mo7y/

Expected output:

Match: Valid prater
p1: Valid prater
Match: Lorem ipsum dolor sit amet, consectetur adipiscing elit.
p1: Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Match: Proin volutpat facilisis imperdiet.
p1: Proin volutpat facilisis imperdiet.
Match: Nunc porttito
p1: Nunc porttito
Match: Morbi non eros nec arcu condimentum ultrices in ut nunc.
p1: Morbi non eros nec arcu condimentum ultrices in ut nunc.
Match: Maecenas elit tellus, scelerisque ac auctor fermentum, bibendum. 
p1: Maecenas elit tellus, scelerisque ac auctor fermentum, bibendum.

I'm looking for similar results as in this example

Actual output:

Match: Valid prater
Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
Proin volutpat facilisis imperdiet. 
 Nunc porttito
Morbi non eros nec arcu condimentum ultrices in ut nunc. 
Maecenas elit tellus, scelerisque ac auctor fermentum, bibendum. 
p1: Valid prater
Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
Proin volutpat facilisis imperdiet. 
 Nunc porttito
Morbi non eros nec arcu condimentum ultrices in ut nunc. 
Maecenas elit tellus, scelerisque ac auctor fermentum, bibendum. 

Can someone explain why I'm not getting the expected output when logging match and p1 to the console?

Why is the behavior different from this example?

What needs to be changed to achieve the expected output?

Thank you!

Answer №1

To leverage the MULTILINE flag or simply m in your regex, allowing the use of anchors ^ and $ to match an entire line in each iteration, follow this method:

let myText = 'Example sentence\nLorem ipsum dolor sit amet, consectetur adipiscing elit. \nProin volutpat facilisis imperdiet. \n Nunc porttito\nMorbi non eros nec arcu condimentum ultrices in ut nunc. \nMaecenas elit tellus, scelerisque ac auctor fermentum, bibendum. '

let paragraphsArray = [];
let dataObject = {};

let extractValues = function(match,p1) { 
  console.log('Match: ' + match);
  console.log('p1: ' + p1);
 };

myText.replace(/^(.*)$/mg, extractValues);

Modified JS Fiddle Link

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

Is using async/await with setState() in React.js the best approach for handling asynchronous operations?

By utilizing async and prevState, I found a solution to console.log the correct state of the page immediately after updating it. As I delved into backend development, I took the time to understand how async operations function. This led me to experiment w ...

Using Node.js with the Instagram API resulted in the error message: "Failed to decode a text frame in UTF-8 format."

For my project, I am utilizing the Instagram API with the http node.js module. The API call is quite simple: getJSON : function(options, on_result, on_error) { var req = http.request(options, function(res) { var output = ''; ...

Learning how to utilize localStorage in conjunction with a color picker to modify the --var of :root

After spending an entire afternoon on my JavaScript issue as a beginner, I have a specific goal in mind: allowing the user to select and change the main color of the page. To implement this, I inserted a color picker in my HTML: <input type="color ...

Node.js equivalent of PHP's SimpleXMLParser

One of the most user-friendly XML reading and writing APIs I've come across is PHP's SimpleXMLElement. For instance, to generate a DOM for the following XML code: <root> <foo> <bar baz="goo"> moo ...

Jquery Deferred failing to activate done or when functions

I'm currently working with 2 ajax calls that I'm connecting using $.when in order to execute certain tasks once they are completed. Below is the code snippet: function ajaxCall(url, targetDiv) { dfd = new $.Deferred(); $.ajax({ ...

Triggering a new window on button click with Vue and Nuxt

Having an issue with a button click event in Vue that opens a PDF using window.open(). It's working well on all browsers except for Safari on MAC. Any ideas what could be causing this? Should I pass $event to the method? <div class="button-do ...

Issue with the functionality of Jquery scrolling through thumbnail images animation

I have encountered an issue related to the previous question that I posted here. After successfully implementing the provided solution, it initially seemed to be working. However, when I clicked the next button and reached the 3rd click, the jQuery scrolli ...

I am encountering an issue with my Javascript file not running due to a bigint error

I'm attempting to utilize @metaplex/js for NFT minting. Usually, my .js files function correctly, but when I execute the file, this particular error arises. bigint: Failed to load bindings, pure JS will be used (try npm run rebuild?) The meaning of ...

Is there a way to cancel a fetch request and initiate a new one right away?

Below is an illustration taken from MDN. The example showcases two buttons - one for sending a request and the other for canceling it. var controller = new AbortController(); var signal = controller.signal; var downloadBtn = document.querySelector(&apos ...

How can JQuery be utilized to extract the information stored in the "value" parameter of a chosen option?

I have a dropdown menu that dynamically populates its options with numbers. Here is the code for that: <select name="TheServices" id="services-selector"> <option value="" disabled selected hidden>Static Select ...

Using regular expressions to eliminate extra spaces using re.sub results in commas following every character

I'm facing a little challenge here and could use some guidance. My goal is to remove duplicate spaces from a string (which is essentially a sentence). Here's the sentence that needs attention: 'Kan me     niks voorstellen   ...

Shut down a pop-up overlay

I've been facing a challenge in implementing greasemonkey to automatically close a modal when the "x" button is clicked. Allow me to share with you the code snippet for the webpage: <div class="modal-header"> <button type="button" class="clo ...

AngularJS: Establishing effective communication channels among directives

I am currently developing a custom directive for an audio player that supports mp3 files. The challenge I'm facing is how to handle multiple instances of the player on a single page. My goal is to ensure that when one player is active, starting anothe ...

SyntaxError: An unidentified item was encountered at the <head> location

I have encountered an issue while loading a PHP file that utilizes ajax. Initially, the page loads without any errors. However, upon triggering the onclick event on a button, I receive the error message "Uncaught SyntaxError: Unexpected identifier" pointin ...

Tips for bringing in and adding an excel spreadsheet to a kendo grid with the help of JQuery

I am facing a challenge with my kendo grid as I am trying to incorporate an excel file into it. Specifically, I would like to import and add an excel file to my kendo grid. If, for instance, my kendo grid initially has 3 rows, after importing an excel file ...

Storing Images in MySQL Database with JavaScript and Node.js: A Step-by-Step Guide

I am using Javascript to capture an image and store it in a MySQL Database. Below is the code I have written for this: <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device- ...

Steps to Retrieve and Showcase a Compilation of YouTube Clips with JavaScript

Recently, I managed to write a C code that retrieves the list of YouTube videos from the URL "*http://gdata.youtube.com/feeds/api/standardfeeds/top_rated*" using the libsoup library. By utilizing libxml2, I was able to parse the XML data and extract specif ...

Adjust CSS classes as user scrolls using skrollr

I am currently facing an issue with the prinzhorn/skrollr plugin when trying to use removeClass/addClass on scroll function. I have attempted to find a solution but unfortunately, nothing has worked for me. <li class="tab col s3"><a data-800="@cl ...

Surprising Outcomes of Negative Margin in jQuery Animation

Unique Project Summary I am currently working on a website that incorporates a sliding menu feature. I have successfully implemented this functionality, and the display remains consistent during the animation transitions for sliding the menu in and out. T ...

Converting PHP variables to JavaScript variables: A step-by-step guide

I'm trying to figure out the most efficient method for retrieving PHP variables using AJAX and then transforming them into JavaScript variables. Imagine I have the following code in my PHP file: echo $total; echo $actual; Edit: JSON echo json_enco ...