Uncover the valuable information within a string using regex in JavaScript

I am looking for a solution to extract key values from a string that looks like this: <!-- Name:Peter Smith --><!-- Age:23 -->

My goal is to create a standard function that can extract any value needed. The function call would be something like: var name=ExtractValue(text,"Name");

Here is my proposed approach:

var text="<!-- Name:Peter Smith --><!-- Age:23 -->"; // Data to be scanned

var name=ExtractValue(text,"Name"); // Get the "Name" key value
var age=ExtractValue(text,"Age");   // Get the "Age" key value
document.getElementById("result").innerHTML = "Extracted name: ("+name+"), age: ("+age+")";

// Function for extracting key values
function ExtractValue(data,key){
    // It should work similarly to /Name:(.*)\s--/
    var rx = "/"+key+"(.*)\s--/";
    var values = rx.exec(data);
    if(values.length>0){
        return values[1];
    } else{
        return "";
    }
}

Any suggestions on how I can achieve this? Thanks for your help!

Answer №1

Here is a way to achieve it:

var text="<!-- Name:Peter Smith --><!-- Age:23 -->"; // Information to be extracted

var name=ExtractValue(text,"Name"); // Retrieving the value for "Name"
var age=ExtractValue(text,"Age");   // Obtaining the value for "Age"
console.log("Extracted name: ("+name+"), age: ("+age+")");

function ExtractValue(data,key){
    var rx = new RegExp(key + ":(.*?)\\s+--");
    var values = rx.exec(data); // Alternatively: data.match(rx);
    return values && values[1];
}

Remember to use double backslashes in a string literal, like "\\s" instead of "\s", to ensure correct interpretation. Also, make sure to include colons in your regular expressions and verify property names such as length for accuracy to avoid logic errors.

Note that exec and match will return null if there is no match, so don't assume the existence of a length property.

Answer №2

This method retrieves an object containing all the identified key/value pairs. Afterwards, users can easily locate specific keys within the object.

var text = "<!-- Name:John Doe --><!-- Age:30 --><!-- Occupation:Developer -->";

var data = ExtractData(text);
console.log(data);
console.log("Retrieved name: (" + data["Name"] + "), age: (" + data["Age"] + ")");

function ExtractData(data) {
  var matches = data.match(/([A-Za-z\s]+:[^\-\-\>]+)/g);
  var extractedData = {};

  if (Array.isArray(matches)) {
    matches.forEach(function(match) {
      var pair = match.split(":");
      if (pair.length === 2) {
        extractedData[pair[0].trim()] = pair[1].trim();
      }
    });
  }

  return extractedData;
}

Answer №3

If you're looking to avoid using regex, consider utilizing the string split function instead.

var text = "<!-- Name:Peter Smith --><!-- Age:23 -->"; // Data that needs to be parsed
var obj = ExtractToObj(text);
document.getElementById("result").innerHTML = "Extracted name: (" + obj["Name"] + "), age: (" + obj["Age"] + ")";

function ExtractToObj(data) {
  var obj = {};
  var kvps = data.split("-->").filter(function(n) {
    return n !== ""; // Remove empty elements
  });
  for (var i = 0; i < kvps.length; i++) {
    var kvp = kvps[i].split(":");
    var key = kvp[0].replace("<!--", "").trim();
    var value = kvp[1].trim();
    obj[key] = value;
  }
  return obj;
}

Here is a demo link on JSFiddle

Answer №4

If I were to approach this task, I might consider the following:

const data = `<div><!-- Name   : Peter Smith --><!-- Age:23 -->some test data that is not found</div>`

const getData = data => {
  const obj = {}, regex = /<!--\s*(.*?)\s*:\s*(.*?)\s*-->/g
  let temp
  while (temp = regex.exec(data)){
    obj[temp[1]] = temp[2]
  }
  return obj
}

const personInfo = getData(data)
console.log(`Extracted name: (${personInfo.Name}), age: (${personInfo.Age})`)

Alternatively, if you only need to extract a single property:

const data = `<div><!-- Name   : Peter Smith --><!-- Age:23 -->some test data that is not found</div>`

const getData = (data, key) => (data.match(new RegExp(`<!--\\s*${key}\\s*:\\s*(.*?)\\s*-->`)) || [, null])[1]

console.log(`${getData(data, 'Name')}`)

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

Navigating the screen reader with the cursor位

Site Design Challenge I recently discovered that the master/detail design of my website is not very accessible. The main view features a column chart where each column represents a different month. Clicking on one of these columns reveals details in a nes ...

When I click the button, it deletes the DOM element and hides it, preventing me from

I'm facing a simple issue that I can't quite wrap my head around. Whenever I input a value into the form and click the button to run the function, the 'loading' element disappears and doesn't reappear. Here is the JavaScript code ...

Difficulty with timing in React.js when rendering content from an Express.js API

I am facing a timing issue while working with React.js. My component checks the validity of the user's token and type. If the user is an admin, it should display certain content; otherwise, it should show "you don't have permission". However, I ...

Having difficulty updating the border color of Material UI Input when it is in focused or unfocused state

I can't seem to figure out why this code isn't working as expected. I'm trying to target the MuiInputBase-root element, specify that it should have a blue border by default, and then change the border color to red when focused. Can someone h ...

Exploring the functionalities of AngularJS' ng-options when working with select elements

In my search through other posts, I came across this issue but couldn't find a solution. Here is the array in question: $scope.items = [ {ID: '000001', Title: 'Chicago'}, {ID: '000002', Title: 'New York' ...

It appears that the jQuery.post() method is being overlooked or bypassed for unknown reasons

Trying to understand why the call to jQuery.post() isn't fetching the data or running the function after the fetch. Three files are included: an HTML file, a JavaScript file, and a PHP file. The HTML contains the modal element intended to appear when ...

Find the identification number by searching through the text

I'm trying to find a way to retrieve the node id during a text search. Here's an example: http://jsfiddle.net/53cvtbv9/529/ I attempted using two methods to get the id of a node after the search: console.log($('#jstree').jstree(true). ...

Utilizing Ionic Storage to set default request headers through an HTTP interceptor in an Angular 5 and Ionic 3 application

I'm attempting to assign a token value to all request headers using the new angular 5 HTTP client. Take a look at my code snippet: import {Injectable} from '@angular/core'; import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from ...

Having difficulty extracting data from certain tables with Beautiful Soup

I have been utilizing BeautifulSoup for data scraping from the website here. Although there are a total of 9 tables with the same class name, I am only able to extract information from 5 of them. What modifications should I implement in my code to ensure t ...

Craft a Flawlessly Repeating Sound Experience - Online

I'm facing a challenge in creating a flawless loop of an audio file. However, all the methods I've tried so far have resulted in a noticeable gap between the end and the start. Here are the approaches I experimented with: The first approach inv ...

ng-options do not refresh automatically when modifying elements in the array

Having trouble updating the data in a select list? It seems that when selecting 'test', the value retrieved from the API is 'Śląsk' even though it's not listed. For example: I select 'test' but it shows as 'Śl ...

Angular library is being excluded from the R.js optimizer process

I'm encountering difficulties when trying to optimize an Angular project with the r.js optimizer. Everything works smoothly when I use grunt-requirejs for optimization, but as soon as I attempt to exclude Angular from the build, I encounter an error ...

Creating Multiple Choice Forms in React: A Guide to Implementing Conversational Form

I've been exploring React (Next.js) and I came across an interesting example of how to use multiple choice in simple HTML on Codepen ([https://codepen.io/space10/pen/JMXzGX][1]). Now I'm curious about how to implement a similar functionality in R ...

Angular.js encountered an error at line 13550: [ng:areq] The argument 'popCntrl' is expected to be a function, but it was undefined

I have been diving into learning AngularJS on my own recently, and I've been attempting to create a basic popup feature. However, I keep encountering the error mentioned in the title. While searching for solutions, I haven't found any examples th ...

Exploring the seamless integration of the Material UI Link component alongside the Next.JS Link Component

Currently, I am integrating Material-UI with Next.js and would like to leverage the Material-UI Link component for its variant and other Material UI related API props. However, I also require the functionality of the Next.js Link component for navigating b ...

Preventing AngularJS from Ignoring HTML Elements

Is there a way to calculate HTML content within an AngularJS object (such as {{names}}) that includes an '<a>' element? When I try to display it, the result looks like this: <a href="http://www.example.com">link text</a> I&ap ...

How can one execute a function within an HTML attribute value using Angular?

I am currently attempting to use the weatherToFontAwesomeIcon(weatherDescription: string) function directly within the HTML file for this component. My goal is to showcase a specific FontAwesome icon based on the weather response from the API. import { Cur ...

Use of image tag inside the title attribute

After coming across the question on how to add an image tag inside the title attribute of an anchor tag and finding only one answer claiming it's impossible, I stumbled upon a page where it was actually done: I decided to view the source of the page ...

Developing a pop-up feature that triggers upon clicking for a miniature rich text editing

Looking to integrate the Tiny rich text editor into my code. Check out the TextEditor.js component below: import React from 'react'; import { Editor } from '@tinymce/tinymce-react'; class App extends React.Component { handleEditorCha ...

How does the Rx subscribe function maintain its context without the need to explicitly pass it along

Currently, I am utilizing Rx with Angular2 and making use of the Subscribe method. What intrigues me is that the callbacks of the method are able to retain the context of the component (or class) that initiated it without needing any explicit reference pas ...