Locating conversation within a block of text using Javascript

Is there a way to extract dialogue, the content between quotes, from a paragraph in javascript and save it in an array?

var myParagraph = '
“Of course I’ll go Kate. You should get back to bed. Would you like some Nyquil or Tylenol?”
“Nyquil, please. Here are the questions and my mini-disc recorder. Just press record here. Make notes, I’ll transcribe it all.”
“I know nothing about him,” I murmur, trying and failing to suppress my rising panic. “The questions will see you through. Go. It’s a long drive. I don’t want you to be late.” “Okay, I’m going. Get back to bed. I made you some soup to heat up later.” I stare at her fondly. Only for you, Kate, would I do this.'

How can I split myParagraph to return an array like:

paragraphArray = ["Of course I’ll go Kate. You should get back to bed. Would you like some Nyquil or Tylenol?",
"Nyquil, please. Here are the questions and my mini-disc recorder. Just press record here. Make notes, I’ll transcribe it all.",
"I know nothing about him,",
"The questions will see you through. Go. It’s a long drive. I don’t want you to be late.",
"Okay, I’m going. Get back to bed. I made you some soup to heat up later."]

Thank you.

Answer №1

const newParagraphArray = myParagraph.slice(1, myParagraph.length-2).split("”“");

This seems to be effective.

Answer №2

Utilizing a regex pattern would be highly effective in this scenario. It is essential to ensure that the quotation marks within the string are standard " quotes, or you can adjust the regex to incorporate directional quotes instead. You have two options:

/"(.*?)"/ for regular quotes; or

/“(.*?)”/ for directional quotes.

The regex "(.*?)" specifically instructs to capture everything between two quote characters with a non-greedy search approach. Additionally, remember to include the g flag in the regex to retrieve all matches rather than just the initial one.

The method .match associated with strings receives a regex input and generates an array of matches. The structure of the resulting array varies depending on whether the regex included the g flag. As we are using said flag here, the output comprises an array of complete matches (inclusive of the surrounding quotes), prompting potential extraction of these quotes from each match result.

For a practical demonstration, consider the following:

var myParagraph = `
"Of course I’ll go Kate. You should get back to bed. Would you like some Nyquil or Tylenol?"
"Nyquil, please. Here are the questions and my mini-disc recorder. Just press record here. Make notes, I’ll transcribe it all."
"I know nothing about him," I murmur, trying and failing to suppress my rising panic. "The questions will see you through. Go. It’s a long drive. I don’t want you to be late." "Okay, I’m going. Get back to bed. I made you some soup to heat up later." I stare at her fondly. Only for you, Kate, would I do this.`

const rgx = /"(.*?)"/g;

const dialogue = myParagraph
    .match(rgx) // Utilize our defined regex pattern 
    .map(result => result.replace(/"/g, "")) // Eliminate quotes from each match result; delete this line if retaining the enclosing quotes is desired 

console.log(dialogue)

Answer №3

If your text block lacks any instances of newline characters, then you have the option to utilize this method.

var myTextBlock = ' “Of course I’ll go Kate. You should get back to bed. Would you like some Nyquil or Tylenol?” “Nyquil, please. Here are the questions and my mini-disc recorder. Just press record here. Make notes, I’ll transcribe it all.” “I know nothing about him,” I murmur, trying and failing to suppress my rising panic. “The questions will see you through. Go. It’s a long drive. I don’t want you to be late.” “Okay, I’m going. Get back to bed. I made you some soup to heat up later.” I stare at her fondly. Only for you, Kate, would I do this.'; 

// captures everything enclosed by “ and ” excluding newline character
// '?' indicates non-greedy search
const regex = /“[^\n]*?”/g;
const result = [];
let match;

// continually push captured content into result array
while (match = regex.exec(myTextBlock)) {
  result.push(match[0]);
}

console.log(result);

You can also choose to eliminate the use of as shown in your query. By utilizing a capture group and pushing its contents into the resulting array instead.

var myTextBlock = ' “Of course I’ll go Kate. You should get back to bed. Would you like some Nyquil or Tylenol?” “Nyquil, please. Here are the questions and my mini-disc recorder. Just press record here. Make notes, I’ll transcribe it all.” “I know nothing about him,” I murmur, trying and failing to suppress my rising panic. “The questions will see you through. Go. It’s a long drive. I don’t want you to be late.” “Okay, I’m going. Get back to bed. I made you some soup to heat up later.” I stare at her fondly. Only for you, Kate, would I do this.'; 

// defines a capture group using `(, )`
const regex = /“([^\n]*?)”/g;
const result = [];
let match;
while (match = regex.exec(myTextBlock)) {
  // modified index number: 0 => 1
  result.push(match[1]);
}

console.log(result);

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

Ways to eliminate numerous if statements in JavaScript programming

Here is the code snippet I'm working with: a = [] b = [] c = [] useEffect(() => { if(isEmpty(a) && isEmpty(b) && isEmpty(c)) { data.refetch() } if(data.isFetching){ //do something } if(response.isFetching){ //do som ...

What could be causing my HTML button to malfunction when attempting to navigate to a different section of the webpage?

Just starting out and developing my website. My hosting provider is IPage, but I'm running into an issue. When I click on a button to switch to another section of the site, it's not working as expected. Here's the code snippet: <button on ...

Achieving consistent text alignment in HTML and CSS without relying on tables

As I delve into the world of HTML and CSS, I've taken a traditional approach by crafting a login page complete with three input controls (two text inputs and one button). To ensure proper alignment of these elements, I initially turned to the trusty & ...

Use HTML to showcase an image that dynamically changes based on the outcome of a query function

Hello there, I hope my inquiry is clear enough. I apologize for reaching out as I am unsure where to begin and what exactly I should be focusing on. Currently, I have an image displayed in an HTML page like this: <div id="tag_sunrise_sunset"><p ...

Sending Multiple Sets of Data with Jquery Ajax.Post: A Step-by-Step Guide

I am currently working with asp.net mvc and I have a requirement to send two sets of database information from jQuery to my Mvc view. Here is an example of how my view looks like: public ActionResult MyView(Product one, Product two) { } Now, my question ...

The function responsiveTable does not exist

I recently added the following code to my aspx page: <script src="../Scripts/jquery.responsivetable.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('#grdStudent').responsiveTable( ...

Is there a way to retrieve values from TextFields and Select elements by simply clicking on a button?

I am currently working on a project using react, redux, and material ui. I need to retrieve data from a TextField in order to make an order. The code snippet below showcases my current implementation: <Select value={product.color_set[0].title}> { ...

The velocity of jQuery selectors

Which is more efficient: using only the ID as a selector or adding additional identifiers? For instance $('#element') vs $('#container #element') or getting even more detailed: $('body div#container div#element') ? ...

Issue with the select element in Material UI v1

I could really use some assistance =) Currently, I'm utilizing Material UI V1 beta to populate data into a DropDown menu. The WS (Web Service) I have implemented seems to be functioning correctly as I can see the first option from my Web Service in t ...

Utilizing Core-TransitionEnd in Polymer: A Beginner's Guide

After a ripple animation on an item has executed, I would like to run a function. Currently, I am using the following code: <post-card id="card1"> <img width="70" height="70" src="../images/start.png"> <h2>P ...

Prevent the generator splitter from generating any null values

With a large number of IDs extracted from a CSV file, I now have a generator of IDs that need to be processed and iterated. To improve efficiency, I've organized these IDs into batches for processing one batch at a time. The code below divides the g ...

fetching numerous JSON documents using jquery

I am struggling to retrieve data from multiple JSON files and display it in a table. Despite being successful in appending data from one JSON file, I encountered issues when trying to pull data from multiple files. Here is my code: var uri = 'sharepo ...

"Integrate the HF push_to_hub API in Google Colab for seamless collaboration

While utilizing Google Colab to upload my fine-tuned model to the Hub, I encountered an issue. Upon running the model.fit() function, a new output directory was created in my Colab drive and the training process began for 2 epochs using my datasets (glue- ...

Converting JSON data to an Excel file in an Angular application

I'm working on exporting my JSON data to an XLSX file. Despite successfully exporting it, the format in the Excel file isn't quite right. Below is the code I am using: downloadFile() { let Obj = { "data": [12,123], "date": ["2018-10- ...

Using the 'client-side rendering' and runtime environment variables in Next.js with the App Router

In the documentation for next.js, it's mentioned that runtime environment variables can be utilized on dynamically rendered pages. The test scenario being discussed involves a Next.js 14 project with an app router. On the page below, the environment ...

After the request.send() function is called, the request is not properly submitted and the page automatically redirects

I'm currently working on a basic ajax comment form that includes a textarea and a yes/no radio button. If the user selects 'yes', their comments are posted and then they are redirected to a new page. If the user selects 'no', th ...

What are some techniques for breaking down or streamlining typescript code structures?

Within my TypeScript class, I have a skip function. In the interface, I've specified that the data is coming from the backend. Now, on the frontend, I want to be able to rename the backend variables as demonstrated below. There are multiple variables ...

Next.js fails to load TailwindCSS

I am in the process of developing an app using tailwindcss and next.js First, I started creating the nextjs app, then I executed these commands: npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p Following that, I made adjustments t ...

Is it possible to run a Universal Windows Platform desktop app on an Android mobile device?

After successfully developing a Universal Windows Platform app in Visual Studio using WinJS, JavaScript, CSS and HTML, I am now interested in leveraging the same code base to create an Android application. Could you guide me on the necessary steps to run ...

Setting the Datetimepicker to be used with every input field

I currently have four textboxes identified by their unique ids: title, sdate, edate, and pdate. My goal is to assign a Datetimepicker to the textboxes that contain the word 'date' in their id. This means I want the Datetimepicker to be assigned ...