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

How to implement an instance method within a Typescript class for a Node.js application

I am encountering an issue with a callback function in my Typescript project. The problem arises when I try to implement the same functionality in a Node project using Typescript. It seems that when referencing 'this' in Node, it no longer points ...

Transferring JavaScript files via Node server using NowJS

As someone new to Node, I need some help with a server-client web application I'm creating for a board game using Raphael for graphics. The issue I'm facing is that while the server successfully sends the HTML file in response to requests, the b ...

VueJS is utilized to duplicate the innerHTML output value

Currently diving into the world of Vue, I encountered an issue while rendering an HTML text. My component template is a WYSIWYG editor. <template> <div id='editor_container'> <slot name="header" /> <div id='editor ...

Toggle the display of dropdown 2 or dropdown 3 depending on the option chosen in dropdown 1

I am struggling with a form that contains 3 dropdowns: <select id="1" required> <option value="">Choose an option</option> <option value="1">Apple</option> <option value="2">Orange ...

``Passing a database value from a controller to a table popup through AJAX: A step-by

I need to display a popup containing data from a database. I'm using an AJAX function with onclick() to achieve this. The data retrieved will be shown in the popup, which includes a table. However, I'm unsure how to properly display the data with ...

What exactly is the mechanism behind the functionality of ng-cloak?

Recently, I've been delving into the ng-cloak source code and trying to understand its inner workings. If you're interested, you can take a look at the source code here. From what I gather, it seems that the ng-cloak attribute is removed during ...

Why does modifying a variable within the fetch URL result in undefined

I currently have a server running on the URL http://localhost:3000/. Within my JavaScript code, I have defined a variable called productCode with the value 'example-code55'. let productCode = 'example-code55'; const fetchData = async ...

Tips for modifiying date format in React app

I'm encountering an issue where I can't modify the date format, preventing me from displaying the date on the frontend. Currently, I'm utilizing the dateformat package. import dateFormat from "dateformat"; const EditFinancialInfo ...

Troubleshooting Node Commands malfunctioning following NodeJS update

I have encountered an issue while trying to update my node version. I deleted the nodejs file from the ProgramFilesx86 folder and then used the Windows installer to install the latest version. However, when I attempt to initialize a node project or use npx ...

Unable to store form data in a JSON file

i need help with the json data file called groups.json { "groups" : [ { "pname" : "group1", "remarks" : "best" }, { "pname" : "group2", "remarks" : "not the best" } , { "pname" : "group3", ...

Printing a modified div element that was created using jQuery on an ASP.NET MVC webpage after the initial page has finished loading

In my view, there is a div that holds multiple tables generated based on the model. Each row in these tables contains fields that can be edited using TextBoxFor. Through jQuery, rows can be moved between tables and new tables can be created dynamically wit ...

What can be done to address the issue of v-model select option onchange displaying the previously selected value or becoming stuck on a static value rather than updating

Whenever I navigate to the message page and select a device, the v-model selected value changes. However, if I go to the device or contact page, the v-model selected value remains unchanged or goes back to the last selected value. Below is the function in ...

``The Art of Handling REST API with Express and Mongoose

Running Express on my application, I have a delete route set up as shown below: router.route('/lists/:id') .delete(function(req, res){ Entry.remove({ _id: req.params.id }, function(err, list){ if(err) ...

Choosing between radio buttons either horizontally or vertically within a table

Here is the markup I am working with: <table> <tr> <td><input type="radio" name="radio"></td> <td><input type="radio" name="radio"></td> <td><input type="radio" name="radio"></ ...

I created an image that can be clicked on, but unfortunately it only functions properly on the

I am currently working on creating an image that can be clicked to cycle through different images all within the same frame. While I have managed to get it to work, I am facing a limitation where it only responds to one click. count = 1; function myF ...

Problem with AWS Lambda function handler failing to insert data into Athena

Trying out a sample code snippet for Amazon Athena to test data insertion, but it's not working as expected. The CloudWatch logs don't show any output after the statement execution is completed. Even when switching to a simple select statement, t ...

Navigating Error: net::ERR_CONNECTION while utilizing Puppeteer

I attempted to utilize a proxy from the following site: Below is my Puppeteer scraping code (deployed on Heroku), encountering an error at the .goto() method, as mentioned in the title: const preparePageForTests = async (page) => { const userAgent = & ...

The functionality of the delete button in Datatables is only operational on the initial page, failing to

My datatable is giving me trouble. The delete button in the action column only works on the first page, but not on the other pages. Here is the code for my delete button: <table id="example" class="table table-striped table-bordered" cellspacing="0" wi ...

Having Trouble with Imported JavaScript File in Astro

Why isn't the js file working in Astro when I try to import or add a source in the Astro file? For example: <script src="../scripts/local.js"></script> or <script>import '../scripts/local.js'</script> I am ...

Determining when all promises have either been rejected or resolved using vanilla JavaScript promises

In an effort to transition to loading all resources in my web application asynchronously using basic JS promises, I have implemented a ScriptLoader function. Below is the code snippet for the ScriptLoader used to load .js files: function ScriptLoader() { ...