Utilize the match() method in JavaScript to target and extract a whole paragraph

I am attempting to extract an entire paragraph from a text file using JavaScript and then display it in an HTML element. Despite reading numerous posts and articles, I have been unable to find the correct regex formula. Here is an excerpt from the text file:

Doing initial required tests

   
   Testing server: xxxxxxxx\yyyyyyyy

      Starting test: Connectivity

         * Active Directory LDAP Services Check
         Determining IP4 connectivity 
         * Active Directory RPC Services Check
         ......................... yyyyyyyy passed test Connectivity



Doing primary tests


The portion I need to extract is from "Starting test: Connectivity" until "passed test Connectivity." This is the JavaScript code snippet I am currently using:

`

async function getText(file) {
  let dcdiagFile = await fetch(file);
  let dcDiag = await dcdiagFile.text();
  let connectivity = dcDiag.match(/Starting test: Connectivity[\n\r]+$(.*)(/gm) || [];
  document.getElementById("DNS").innerHTML = connectivity;
  console.log(connectivity);
}
getText("./dcdiagreport.txt");

` With my current implementation, I only retrieve the first line of the paragraph. I initially thought that the wildcard operator would help with this issue, but including the word Connectivity in the regex pattern as below does not yield any results:

let connectivity = dcDiag.match(/Starting test: Connectivity[\n\r]+$(.*)Connectivity (/gm) || [];

In other programming languages, I would use a "text beginning * text ending" approach to extract the paragraph, however, it seems different in JavaScript. Since I am working on intranet servers without internet access, I prefer not to download jQuery and stick to vanilla JS only.

Answer №1

If you prefer, you can opt for using a .replace() method instead of a .match() to filter out only the necessary text.

It's unclear whether you want to include or exclude the phrases "Starting test: Connectivity" and "passed test Connectivity". Below is a code snippet featuring regex1 which includes those phrases, and regex2 which excludes them:

const input = `Doing initial required tests
      Testing server: xxxxxxxx\yyyyyyyy

      Starting test: Connectivity

         * Active Directory LDAP Services Check
         Determining IP4 connectivity 
         * Active Directory RPC Services Check
         ......................... yyyyyyyy passed test Connectivity

Doing primary tests`;

const regex1 = /^.*?(Starting test: Connectivity.*?passed test Connectivity).*$/s;
let connectivity1 = input.replace(regex1, '$1');
console.log(connectivity1);

const regex2 = /^.*?Starting test: Connectivity\s*(.*?)\s*passed test Connectivity.*$/s;
let connectivity2 = input.replace(regex2, '$1');
console.log(connectivity2);

Explanation of regex1:

  • ^ -- denotes start of text
  • .*? -- non-greedy search
  • ( -- beginning of capture group 1
  • Starting test: Connectivity -- literal text anticipated
  • .*? -- non-greedy search
  • passed test Connectivity -- literal text anticipated
  • ) -- end of capture group 1
  • .* -- greedy search
  • $ -- marks the end of text
  • /s -- modifier s helps integrate newlines in .

Explanation of regex2:

  • similar process to regex1, but with a more specific capture group

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

"Implementing a feature in Django that clears the input field upon clicking the clear button

I am working on a Django HTML file that includes an input field and a clear button. I need to clear the input field when the clear button is pressed. Is it necessary to use JavaScript for this task, or is there another way to achieve it? <form> ...

Challenges encountered with input outcomes

I am facing an issue with input results. I have a button that triggers a function to check for empty input fields. However, when I click the button, it always falls into the last if statement and displays as if the fields are not empty. I have already att ...

I'm facing an issue in React where using onChange is causing all DOM elements to be cleared. The input form functions correctly when used with a button, but for some reason, the onChange event does not

Currently, I'm working on a grid that can be resized using two input fields in the application. The setup involves an input for cells across, an input for cells down, and a button to set the grid, which is functioning well. However, I would like to ma ...

jquery makes it easy to create interactive hide and show effects

The main concept is to display the element upon clicking and hide it when there is any mouse click event. Below is the HTML code I'm using: <ul> <li> <span class="name">Author 1</span> <span class="affiliation"&g ...

Can AJAX be considered a backend tool for retrieving data from servers?

I'm curious to find out if ajax is primarily used as a backend technology for retrieving data or if it's mainly considered a frontend tool. My attempts to research this on Google have not yielded a definitive answer. ...

Adjusting the overflow of a parent div based on the position of the div within it by scrolling

I'm trying to create a page with 3 different sections: <div class="container" id="main-container"> <div class="section" id="profile"> Hello World </div> <div class="section" id="projects"> Hello World 2 ...

Error: The 'then' method cannot be invoked on an undefined object in the Parse.File.save function

I am currently utilizing the Javascript API for parse.com within an Angular JS application. My goal is to successfully save or update the user's profile picture. Below is the code snippet that I have been working with: Some HTML . . . <input type ...

Apologies, but Discord.js is unable to access the property "user" of a null object

I am facing a perplexing issue that I cannot seem to wrap my head around. The function works perfectly on one server but fails on another. Below is the snippet of code in question: const user = message.author; let servericon = message.guild.iconURL; let se ...

What is the main object used in a module in Node.js for global execution?

Node.js operates on the concept of local scope for each module, meaning variables defined within a module do not automatically become global unless explicitly exported. One question that arises is where a variable declared in a module file belongs in term ...

Could my mental model be flawed? When a page is accessed using https, a relative css path will be invoked using the same protocol

When your page is accessed using the https protocol, any relative path to an external CSS file will also be called using the https protocol. Do you really need to encrypt/decrypt CSS content? :D However, if you use an absolute path to reference an external ...

jQuery ceases to function once AJAX content is loaded

Exploring Options for Flexible Data Display I'm currently in the process of building a webpage that allows users to choose between different layouts for loading data. This includes the option to display data in either a list format or a card interfac ...

Animating each individual element within the v-for loop in Vue.JS

Recently, I developed a basic to-do app using VueJS. Additionally, I integrated vue2-animate, which is a Vue.js 2.0 adaptation of Animate.css used for Vue's built-in transitions. The animation feature that adds an element functions correctly. However ...

Transforming the *.vue file into a *.js file for deployment on a content delivery network

Is there a way to compile Component.vue files into JavaScript files for use with the Vue CDN in HTML? For example, consider the following component Component.vue: <template> <div class="demo">{{ msg }}</div> </template& ...

ReactJS encountering an invalid dropzone element

Encountering the error "invalid dropzone element". I added var Dropzone = require('react-dropzone'); to my webpack.config.js file in hopes of activating the Dropzone element. This is what is included in my JavaScript file, copied from a Gith ...

Accessing Private Files with Signed URLs from AWS S3

Issue: The challenge is to securely allow users to upload a file and retrieve it later. The files are stored in private Buckets and objects using S3 pre-signed URLs for uploading. However, fetching the file poses a problem as the signed URLs expire after ...

Deactivating a button if the input fields are blank using ReactJS

Hi there, I'm new to reactJS and recently encountered an issue with my code. Everything seems to be working fine except for the NEXT button not being disabled when text fields are empty. My expectation is that the NEXT button should only be enabled af ...

Tips for retaining JWT token in local storage even after a page refresh

I am currently working on implementing a login/logout feature and utilizing the context API to manage functions such as storing tokens in local storage and removing them upon logging out. However, I have encountered an issue where the token stored in local ...

Having trouble getting my parallax slideshow to work with jquery preventDefault

-UPDATE- After countless hours of online courses, tutorials, and programming, I finally completed my website! Check it out here: The site is almost where I want it to be, but there are a few remaining challenges: 1) AJAX: I'm struggling to get the ...

Slide containing Ionic list views

In my Ionic app, I am using ion-slide-box with 3 slides. Each slide contains an ion-list (table view) with varying numbers of items. The issue is that when scrolling through the shorter list items, it shows empty content due to the taller sibling list taki ...

Is there a way to retrieve the input element's value within the controller using ng-if?

After clicking on the submit button, I want the ng-if condition to activate in the DOM so that I can access the properties of the input element or apply a class to it. <div ng-app="myModule"> <div ng-controller="myController"> <div ng-if ...