Is there a way to use regular expressions in JavaScript to match tags

As I am not very experienced with regex, my goal is to extract content from the <text> tag and the <music> tag within the given string. The expected result will be two arrays as shown below:

The string to match:

"<text>Chủ nhật, ngày 24 tháng 5 năm 1863, giáo sư Lidenbrockenbrock vội vã trở về ngôi nhà của ông ở số 19 đường Konigstasse, nằm trong khu phố cổ kính nhất ở thành phố Hambourg.</text><music>abc.wav</music>"

Result:

["Chủ nhật, ngày 24 tháng 5 năm 1863, giáo sư Lidenbrockenbrock vội vã trở về ngôi nhà của ông ở số 19 đường Konigstasse, nằm trong khu phố cổ kính nhất ở thành phố Hambourg."]

and

["abc.wav"]

Answer №1

After encountering issues with the code provided by @taggon not functioning properly with strings containing line breaks such as \r\n, I made a slight modification to address this issue. Here is the updated version:

STRING_TO_MATCH = STRING_TO_MATCH.replace(/(?:\r\n|\r|\n)/g, '<br/>');

/**
 * If <music> always follows <text>
 */
var matches = /<text>(.+?)<\/text>\s*<music>(.+?)</music>/.exec(STRING_TO_MATCH);
var text, music;
if (matches) {
    text = matches[0]; // <text> content
    music = matches[1]; // <music> content
}

/**
 * Otherwise 
 */
var text = /<text>(.+?)<\/text>/.exec(STRING_TO_MATCH);
var music = /<music>(.+?)<\/music>/.exec(STRING_TO_MATCH);
if (text) text = text[0];
if (music) music = music[0];

Answer №2

Are arrays necessary in the output? The code provided allows you to extract the desired content, excluding arrays. To include arrays, simply encapsulate the content within them.

/**
 * If <music> always follows <text>
 */
var matches = /<text>([\s\S]+?)<\/text>\s*<music>([\s\S]+?)<\/music>/.exec(STRING_TO_MATCH);
var text, music;
if (matches) {
    text = matches[0]; // <text> content
    music = matches[1]; // <music> content
}

/**
 * Otherwise 
 */
var text = /<text>([\s\S]+?)<\/text>/.exec(STRING_TO_MATCH);
var music = /<music>([\s\S]+?)<\/music>/.exec(STRING_TO_MATCH);
if (text) text = text[0];
if (music) music = music[0];

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

What is the best way to incorporate tooltips in SVG?

My teacher wants me to display a tooltip on an SVG circle with links and information when we hover over it. They suggested using jQuery UI, but I've done extensive research and nothing has been able to assist me so far. ...

Tips for extracting values from a JSON object in Angular when dealing with a JSON string

Storing column values as a json string in the DB table and then sending them to the front end as a json object. [ { "jobId":"efe0ace0-8ed9-45ff-9232-974cbdc89b86", "jobType":"TestExecutionJob", "nextRun":"N/A", "lastRun":"20 ...

Implement feature to enable selection using jQuery

I have a question about implementing an <option value="fiat">Fiat</option>"> element into a dropdown list using jQuery. I've tried the code below and encountered some issues. When I click the button, I want to add the <option value= ...

Another option to avoid using complicated else if chains

I'm facing a challenge with a function that returns a value known as user_id. It involves multiple conditions that need to be checked. First condition: Verify the service variable Second condition: If not found, retrieve user_id from local storage ...

Guide on creating a 4-point perspective transform with HTML5 canvas and three.js

First off, here's a visual representation of my objective: https://i.stack.imgur.com/5Uo1h.png (Credit for the photo: ) The concise question How can I use HTML5 video & canvas to execute a 4-point perspective transform in order to display only ...

The file that is currently being downloaded has the .pptx extension, but it is being

Take a look at this code snippet: const generateDownload = ({ link, data, title, settings })=> { const newLink = document.createElement('a'); const blobUrl = link || URL.createObjectURL(new Blob([data], settings)); newLink.setAt ...

Error 504 'FUNCTION_INVOCATION_TIMEOUT' encountered on NextJS/Vercel deployment

Encountering an error on one of my pages after deploying to vercel, everything functions properly in dev mode. I suspect the issue lies with one of my fetch/APIs as it utilizes the data from the initial fetch request as the URL for the subsequent fetch re ...

Unable to access serialized select2 value in asp.net mvc controller

I'm facing a challenge with serializing and passing multiple controls inside a div to a controller via AJAX in my view. One of the fields, SchoolType, is a select2 multi-select dropdown. Model : public class SchoolModel { public string StudentN ...

What is the best way to change JSON into a string format?

Similar Question: Converting JavaScript Object to JSON String I am dealing with a JSON object in JavaScript and I need to change it into a string. Is there a specific function I should use for this conversion? Appreciate any assistance, ...

"Enhance your Highcharts experience with dynamic visualization and maximize the number of

When creating dynamic highcharts, I utilize the series.addPoint method. While it successfully adds points, the chart does not move as shown in this example - jsfiddle. This results in potentially having 100 points on the screen. How can I limit the displ ...

Implementing real-time data visualization by dynamically updating a line graph on a website using information retrieved from a Java

Currently, I have a java application running on one PC and a web application consisting of javascript, html, and bootstrap hosted on a tomcat server on another PC. The java application includes two variables within a class - distance and time - that are c ...

Error encountered while rendering a functional component in ReactJS

Recently, I've been utilizing functional components in my project, like this: const Component = (props) => <div>asdasdasd</div>. However, I'm encountering a cryptic error when trying to render my application. The console displays a ...

Using Node.js for HTML redirections involves creating routes and setting

I am currently attempting to connect my Node.js API with my HTML pages. For the most part, everything is functioning correctly, but I have encountered some confusion along the way. Is there a more efficient method for redirecting an HTML page? Typically, ...

What is the best way to determine in component.html whether the column type is equal to 1 to show the label text "Active,"

Having trouble checking the value of an object named ReportControl. If the column type is 1, display the label "active"; otherwise, display the label "not active" on reportcomponent.html. The data for the ReportControl object is as follows: {"reportId": ...

A guide on creating a Utility function that retrieves all elements in an array starting from the third element

I've been working on a tool to extract elements from an array starting after the first 2 elements. Although I attempted it this way, I keep getting undefined as the result. // ARRAYS var arr = ['one', 'two', 'three', &a ...

What is the best way to retrieve the row IDs in react-table?

Using table-v7 and attempting to implement a delete modal, but unsure of how to retrieve the ids of my rows and set them in my axios request The function is located in a hook file, and if I use row.original._id, I can obtain the id but it only works withi ...

Redux - Preventing Overwriting of Product Quantity in Cart by Creating a New Object

Is there a way to address the issue where adding the same product multiple times to the cart creates new objects instead of increasing the quantity? switch (action.type) { case actionTypes.ADD_TO_CART: const product = state.products.find((p) = ...

Turn off Closure Compiler formatting guidelines

I've inherited an old codebase that's been minified using Closure Compiler. As part of our efforts to modernize and optimize the code, we've set up a CI job to highlight any warnings or errors. However, some of these warnings are irrelevant ...

Google Maps Circle Radius Functionality Malfunctioning

I've been trying to implement a map scaling feature using a slider in my code but I'm having trouble getting it to work. While the map is displaying correctly, the radius won't update as intended. Any assistance with this would be greatly ap ...

Client-Specific User Portal

Looking for some support on the back end of things. We are in the process of creating a portal where users will be directed to their specific landing pages upon logging in, providing access to files they have signed up for. Our team is exploring the use ...