A pattern matching formula to eliminate specific characters from the beginning to the end of a string

I am facing an issue with extracting content from a given string:

var string = "From: Sarah<br />
 Sent: 10 May 2021 09:45:20</br />
 To: Alice<br />
 Subject: Meeting Reminder<br /><br />

 Hi Alice, 
<br />
Here is a reminder about our meeting tomorrow. 
<br />
See you then! 
<br />
Sarah"

I need to extract the email body content starting from the line after the "Subject" line in the given string.

My current approach involves using the substring method like this:

string.substring(string.lastIndexOf('Subject'), string.length - 1)

However, this approach also includes the "Subject" line in the extracted content which is not desirable. Is there any regex library or alternative method that can help me achieve the desired result?

Answer №1

To utilize the string.replace method, you can implement the following:

var message = string.replace(/^[\s\S]*\s+Subject: [^\n]*\n+/, '')

Implementation:

var string = `From: Jenna<br />
Sent: 18 May 2021 09:45:21</br />
To: Alex<br />
Subject: Test email content<br /><br />

Hi Alex,
<br />
This email is to test the emailing system.
<br />
Thank you,
<br />
Jenna`

var body = string.replace(/^[\s\S]*\s+Subject: [^\n]*\n+/, '')

document.writeln("<pre>" + body + "</pre>")

The pattern [\s\S]* matches zero or more of any characters, including newline. It then removes the line containing "Subject:".

Result:

"Hi Alex,
<br />
This email is to test the emailing system.
<br />
Thank you,
<br />
Jenna"

Answer №2

While others may offer a non-regex solution, here is one that uses regex

[\s\S]*Subject\s*:.*([\s\S]+) <-- the desired result will be in the first capturing group

Check out the Regex Demo here

See it in action with this JavaScript demo

var re = /[\s\S]*Subject\s*:.*([\s\S]+)/gm; 
var str = `From: Jeremy<br />
Sent: 22 Apr 2016 12:08:03</br />
To: Mark<br />
Subject: Another test email<br /><br />

Hi Mark, 
<br />
I'm sending this email as a way to test the email! 
<br />
Cheers, 
<br />
Jeremy`
var m = re.exec(str);
document.writeln("<pre>" + m[1] + "</pre>");

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

Building a bridge between React Native and MongoLab

I am currently in the process of developing a React Native application for iOS that will require querying a database. After some research, I have chosen to use MongoLab. Upon reviewing MongoLab's documentation, it is suggested to utilize the MongoDB D ...

Comparing values between two JSON objects in Angular 8: A guide

I need to compare the values of two objects, obj1 and obj2, by ignoring keys that are missing in either object. If all key-value pairs are equal, return false; otherwise, return true. For example: If 'id' is present in obj1 but not in obj2, it s ...

Tips for injecting scripts into the head tag after an Angular component has been loaded

Currently, I am facing an issue with a script tag containing a Skype web control CDN. The script has been placed in the head section of my index.html file, but it is being called before the component that needs it has finished loading. Does anyone have a ...

Guide on properly documenting custom function types in JSDoc or TypeScript to ensure accurate referencing for VSCode IntelliSense functionality

I am currently working on documenting custom function types within an object and would greatly appreciate any assistance: A Closer Look at the Issue Consider this basic object declaration with several function properties (addCoordinate, addCoordinateOne, ...

Executing a php function upon onchange event triggered by CKEditor

My task involves invoking a PHP function when I suspect it is being triggered by an ajax call. Utilizing ckeditor, I aim to detect any keyboard activity and believe that using onchange will serve this purpose. Subsequently, I plan to execute a function t ...

Is there a way to streamline a function that substitutes certain words?

Looking for ways to simplify my function that shortens words when the label wraps due to different screen resolutions. It seems like it could be more efficient to use arrays for long and short word pairs, but I'm not sure how to implement it. Check ou ...

Tips on implementing live updates in Firebase without the need for reloading the page

After a user changes their profile picture, the update does not appear until they refresh the page. Here is the code snippet causing this issue: const handleProfile = async (e: any) => { const file = e.target.files[0] const storageRef = firebase ...

Tips for preserving a string in angularJS or Java (and implementing it in an iframe)

My plan involves utilizing a Java web service to fetch the HTML content from a specific URL using Jsoup, and then returning it as a string to the requesting party, which could be an Angular or JS script. I am keen on preserving this content somewhere and l ...

Generate an image, PDF, or screenshot of a webpage with the click of a button

I've been searching for a solution that would enable users to click a button and save an image or PDF of the current page. The content on the page is dynamic and dependent on user input, resulting in sequences displayed in various colors. I'm loo ...

Creating a nested tree structure array from a flat array in Node.js

I have an array structure that I need to convert into a tree array using node.js. The current array looks like this: var data= [ { "id1": 1001, "id2": 1002, "id3": 1004, ... } ...

Combining TypeScript and JavaScript for efficient mixins

I came across an article on MDN discussing the usage and creation of mix-ins (link). Intrigued, I decided to try implementing it in TypeScript: type Constructor = new (...args: any) => any; function nameMixin(Base: Constructor) { return class extends ...

Task: Choose MySQL option and Retrieve JSON data

I have a question regarding implementing a function in a separate module file and calling it within a route to retrieve query data: function getSobre() { return new Promise((resolve, reject) => { db.query(`SELECT * FROM sobre ORDER BY cod ...

Incorporate a map (using leafletjs or Google Maps) as a subtle backdrop

I am currently working on a one-page website and I would like to include a map as a background behind the "contact" section. The map can be set to float, draggable, or positioned at the back. I have experience using both the Google Maps API and LeafletJS, ...

Developing dynamic HTML content using Android and JavaScript to insert JavaScript code into the head tag dynamically

I need to incorporate a banner into my Android application in a specific way. Upon receiving the following Javascript code from the server: <script type="text/javascript" src="http://rm.face.ua/adriver.core.2.js"></script> <div id="adri ...

Applying binary information to an image

Let's say I have an <img/>. The img is initially set with src='http://somelocation/getmypic'. Later on, there might be a need to change the content of the image based on some ajax call that returns binary data. However, this decision c ...

Is it possible to refresh HTML content using jQuery?

Currently, I am attempting to iterate through response data and integrate the values into the HTML of my webpage. It's crucial for me to clear any existing values in the HTML so that only the new ones are displayed, keeping it up-to-date. The structu ...

Issue with React's handleChange function in two separate components

I need assistance with calling the event handleChange from a second Component This is my principal component: const [mainState, setMainState] = useState({ stepValue: 1, saleDateVal: new Date(), customerVal: '' }); function moveNextStep() { ...

Hey there, I'm looking to use different CSS fonts on Windows and Mac for the same page on a web application. Can someone please guide me on how to accomplish this?

In order to tailor the font based on the operating system, the following criteria should be followed: For Windows: "Segoe UI" For Mac: "SF Pro" Attempts have been made using the code provided below, but it seems to load before the DOM and lacks persisten ...

Interactive jQuery tabbed interface with drop-down selectors, inconsistent display of drop-down options when switching between tabs

After receiving assistance from members oka and Mike Robinson, I have successfully created two tables for users to interact with using tabs and dropdowns. Both tables have the same structure and feature a dropdown menu to show/hide columns. Users can sele ...

Having trouble with submitting a form through Ajax on Rails 4

Having models for advertisement and messages with forms that both utilize Ajax (remote => true) for submission. The message form submits perfectly, remains on the same page, and handles the response efficiently. However, the advertisement form fails to ...