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

Building nested routes in a protected path using react-router version 6

At the moment, I am utilizing react-router-dom version 6.1.1 and I have a private route in use. Typically, within this private route, I include other routes to maintain my Sidebar. This is how my code appears: // App.tsx const RequireAuth: React.FC<P ...

Managing state changes in React can be a complex task, but

As a newcomer to React, I am currently working on creating an icon menu. However, I am facing an issue with my handleChange function not functioning as expected. While the icon Menu and possibleValues menu are visible, I am unable to select any of the op ...

Execute Cheerio selector once the page has finished loading

Hey there! I'm trying to extract the URL value of an iframe on this website: I've checked the view page source but couldn't find the iframe. Looks like it's loaded after the page is fully loaded through JavaScript. Could it be that ...

An array containing concatenated values should be transferred to the children of the corresponding value

Consider this example with an array: "items": [ { "value": "10", "label": "LIMEIRA", "children": [] }, { "value": "10-3", "label": "RECEBIMENTO", ...

html input type called array named AmountMap[1] is unable to be configured with <input type="textbox" size="15" name="amountMap[1]" value="0" >

**Having trouble setting the value of an HTML input type named like an array AmountMap[1] <input type="textbox" size="15" name="amountMap[1]" value="0" > When trying to set amountMap[1].value='10', ...

Protractor: Locating Elements Based on Attributes

I have been looking for a specific element to test: <div class="alert alert-danger" role="alert" ng-show="notValid">Zugangsdaten eingeben</div> How do I locate this element to verify its visibility based on the ng-show attribute? The ng-show ...

The mystery behind the enigmatic combination of ajax, JQuery,

Seeking Assistance! All fields are displaying undefined values function UpdateData(){ var id = $('#id').attr('value'); var name = $('#name').attr('value'); var department = $('#departament'). ...

Avoiding the utilization of automatically generated JSON files as a data source in Rails when

I have implemented javascript code that uses JSON to generate a timeline. The JSON is being created using json_builder and it contains only the current user's information. The JSON displays correctly when accessed directly through its URL, but when th ...

Leveraging Google maps to find nearby stores

I recently created a store locator but hit a roadblock when I discovered that Google Maps does not allow you to iframe the entire page. Is there a workaround for this issue to display the map? Or is there an alternative method that doesn't involve ifr ...

Save the value of a promise in a variable for future use in state management within a React-Native application

let storage = AsyncStorage.getItem('@location_data').then(data => data) const MainApp = () => { let [currentLocation, setCurrentLocation] = useState(storage); The current situation is that the storage variable holds a promise. How can ...

Oops! The Vue star rating encountered an error because it couldn't read the length property of an undefined value at line 26 of listToStyles.js

Encountering an issue with the getRating function in Vue while using the Vue-star-rating package in Laravel. Unsure of what the problem may be. getRating(){ var pathArray = location.pathname.split('/'); v ...

The AngularJS templates' use of the ternary operator

Is there a way to implement a ternary operation in AngularJS templates? I am looking for a way to apply conditionals directly in HTML attributes such as classes and styles, without having to create a separate function in the controller. Any suggestions wo ...

Multiple occurrences of setting the state on an array result in logging an empty array each

My current challenge involves fetching data from a backend server and storing it in an array. However, when I attempt to pass this array to another component, I encounter an issue where multiple empty arrays are being passed instead of one filled with data ...

Vue.js transition-group does not apply the *-move class

As I dive into learning Vue, I find myself wondering if I may have overlooked something fundamental or stumbled upon a bug. Despite multiple readings of the documentation at https://v2.vuejs.org/v2/guide/transitions.html#List-Move-Transitions, I still can& ...

hybrid application combining AngularJS with Angular 17 and above versions

I have been attempting to set up a hybrid environment with both AngularJS and Angular 1.7+ running side by side. I diligently followed all the guidelines and even created a custom webpack configuration to bundle my AngularJS and Angular files together. The ...

AngularJS directive error: Incorrect function invoked

I have two similar scenarios where I need to apply validators for specific files, even though I am aware that this goes against the DRY principle. However, being new to AngularJS, I am still learning the ropes. module.js var $moduleExample = angular.modu ...

Sweet treats, items, and data interchange format

Can an object be converted to a string, stored in a cookie, retrieved, and then parsed back to its original form when the user logs on again? Here's a concise example of what I'm asking: var myObject = { prop1: "hello", prop2: 42 }; va ...

Material UI DateTimePicker Displaying Incorrectly

I am implementing a new Material UI date time picker on page load by setting the open prop. <Grid item xs={6} className={styles.CampaignDates_calendar_right}> <MuiPickersUtilsProvider utils={DateFnsUtils} className={styles.CampaignDates_calendar ...

How to Retrieve Superclass Fields in Angular 5 Component

I have a superclass that provides common functionality for components. export class AbstractComponent implements OnInit { public user: User; constructor(public http: HttpClient) { } ngOnInit(): void { this.http.get<User>(& ...