Using Javascript to merge two standard expressions

Does anyone have a regular expression that can accurately identify the author in these scenarios?

Letter from author to recipient regarding topic 11-10-2018

Letter from author, regarding topic 10-11-2018

I attempted to use the advice provided on this website, and this is what I came up with:

let commaRegex =  new RegExp(/(?<=from) (.+?),/, 'gi','$1');
let fromToRegex = new RegExp(/(?<=from) (.+?) (?=to)/, 'gi','$1');
let combinedRegex = new RegExp(commaRegex + '|' + fromToRegex);
let author = document.getElementById('userInput').value.match(combinedRegex);
console.log(author) 

However, when I run console.log(author), it returns 'null'.

I am aware that look behinds are not supported in all browsers, so I am using this code on Chrome. Does anyone have any other suggestions?

Answer №1

If you want to avoid automatic combination of elements, simply use the or operator for the final part:

(?<=from )(.+?)(?=,| to)

https://regex101.com/r/xzlptd/2/

To ensure compatibility with all browsers, remove the look-arounds from your expression:

from (.+?)(?:,| to)

Then extract the first group from the match using .match(...)[1]

Answer №2

Aside from the solution offered by georg, if you find yourself needing to merge two different things that can't simply be replaced by one:

Rather than including the entire object, you need to add the sources individually:

let commaRegex =  new RegExp(/(?<=from) (.+?),/, 'gi','$1');
let fromToRegex = new RegExp(/(?<=from) (.+?) (?=to)/, 'gi','$1');
let combinedRegex = new RegExp(commaRegex.source + '|' + fromToRegex.source);

let sampleText = 'Letter from Joseph Tribbiani to recipient regarding topic 11-10-2018';

console.log(sampleText.match(combinedRegex));

sampleText = 'Letter from Joseph Tribbiani, regarding topic 11-10-2018';

console.log(sampleText.match(combinedRegex));

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

Issue with z-index causing the image to not display when navigating through an image gallery with previous and next buttons using

$(document).ready(function(){ $(".divs div.panel").each(function(e) { if (e > 2) $(this).hide(); console.log(e); }); $("#next").click(function(){ if ($ ...

The new pop-up window appears smaller than expected in Internet Explorer

There has been a bug report regarding the course opening in a smaller popup window. The JavaScript code used to open the popup is: course_window=window.open(urlString,"", "toolbar=0,directories=0,location=0,status=0, menubar=0,fullscreen=0,scroll ...

Execute a function (with arguments) within a v-for loop in Vue.js

Currently, I am attempting to create a select element using Vue.js and Material Design that has 2 levels: categories and items. Each category can contain multiple items which may be selected or not. <md-select v-if="categories.length > 0" name="cate ...

Gulp encountered an issue - Module 'sigmund' not found

After installing browser-sync, my previously working Gulp encountered an error: Error: Cannot find module 'lru-cache' To resolve this issue, I utilized the following solution: npm link lru-cache as suggested in this thread However, upon atte ...

Encountering a 404 error in a Next.js application while utilizing path parameters

Embarking on my journey into web development, I am trying to grasp the concept of server-side rendering using next.js and react within a lambda function. When running the code on a lambda, the result is somewhat functional as it displays the parameter valu ...

Restore the initial content of the div element

Currently, I am utilizing the .hide() and .show() functions to toggle the visibility of my page contents. Additionally, I am using the .HTML() function to change the elements inside a specific div. $('#wrap').html(' <span id="t-image"> ...

Formik: encountering target as undefined while passing Material UI Date Picker as prop to React Component

I'm currently working on developing a component that can be reused. The idea is to pass form fields as props, but I ran into an issue when clicking on the datepicker field. The error message that pops up is: TypeError: target is undefined Any sugge ...

Import failures in Three.js could be attributed to potential issues with Webpack

Please note: I am utilizing create-react-app along with three.js v0.99.0. In my current project, I am faced with the challenge of importing specific modules from three.js to avoid bundling the entire library, which results in a large uncompressed file siz ...

show the attributes of an item contained within an array of objects

Hey there! I'm facing an issue with displaying the content of an object on my HTML page using React. So, here's what's happening: I can access the frontend properties in my object array, but when I try to loop through each element and displa ...

Adjust the font size to fit within the container

My webpage features a bootstrap 4 container with three columns that adjust on screen sizes above the md breakpoint (col-md-4). Each column contains an img with the class img-fluid, and when hovered over, text description appears. I want this hover text to ...

Accessing the camera or photo library in React Native does not require any permissions

In my current project, I am developing an app that requires users to upload images from their photo library or camera. To access the camera functionality, I am utilizing the react-native-image-picker library without integrating react-native-permissions. ...

Sorting an array using the Insertion sort algorithm in JavaScript / An undefined function

Currently, I am in the process of developing a JavaScript file that includes an insertion sort function, a method to validate a sorted array and return true or false, and a reverse insertion sort function that operates from the end of the array index towar ...

Using Jquery to delete the parent element containing text that does not match

I need to search for text in a table cell that matches the text in an h1 heading and then eliminate all other table rows containing text that does not match. The code snippet provided only works if there is one .tablerow with a .tablecell, so I am looking ...

Creating a see-through backdrop using three.js

I am facing an issue with setting a transparent background to the canvas using three.js. My code is: Background.renderer.setClearColor(0xffffff, 0); However, the background turns black instead of being transparent. How can I make it transparent? Here is ...

unable to retrieve the li element's ID when clicked

I am working on a code snippet to display tabs with dynamic content. $start = strtotime($_GET['date']); $dates = array(); for ($i = 0; $i <= 7; $i++) { $date = date('Y-m-d', strtotime("+$i day", $start)); $date1 = $ ...

Tips on avoiding the default action during a keypress for specific events before eventually restoring the default action

I've been experimenting with a project that involves using the space bar to trigger an event. It's actually quite complex, but I simplified it for this example. The concept is that when the space bar is held down, it highlights a certain div, an ...

The function d3.geoStitch has not been defined

I am currently working on implementing this example that visualizes a TIFF file using d3 as a node script. Everything seems to be functioning well, except when it comes to d3.geoStitch where my script throws an error stating d3.geoStitch is undefined. The ...

Filter out <li> elements by child data attribute

Below is an example of the HTML code I am working with: <li><div class="abc"><a href="https://www.google.com" data-test="male">John</a></div></li> <li><div class="abc"><a href="https://www.facebook.com" d ...

Retrieving HTML content from a React array

One challenge I am facing is how to include HTML content inside a React array that I will use in the render method. To begin with, I start by creating my content using the following approach: let resultHtml = []; resultHtml.push(<p key="resultScore"&g ...

Tips for aligning a mesh on the X and Y axes in three.js

Currently, I am aligning objects/models (mesh) in my scene by using the mesh.geometry.center() function. This method helps position the object in the center based on its bounding box. For static objects with a fixed size, like a cardboard box for example ...