Duefectu
Duefectu

Reputation: 1642

Extract key value from string with regex in JavaScript

I need a function to extract key values from an string like this: <!-- Name:Peter Smith --><!-- Age:23 -->

I want to make an standard function to extract any value. The call is something like this: var name=ExtractValue(text,"Name");

This is my 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 extranting key values
function ExtractValue(data,key){
    // It's try to be like /Name:(.*)\s--/
    var rx = "/"+key+"(.*)\s--/";
    var values = rx.exec(data);
    if(values.lenght>0){
        return values[1];
    } else{
        return "";
    }
}

How can I do this? Thanks for your time!

Upvotes: 1

Views: 4013

Answers (4)

trincot
trincot

Reputation: 350212

You can do it like this:

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
console.log("Extracted name: ("+name+"), age: ("+age+")");

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

Don't forget to escape backslashes in a string literal. So "\\s" instead of "\s", as the latter would be exactly the same as "s". Also, the colon was missing in your regular expression. Finally, you had a spelling mistake in the length property name, so your if condition would always be false.

Be aware that exec and match will return null when there is no match, so you should not assume there is a length property.

Upvotes: 3

Maciej Kozieja
Maciej Kozieja

Reputation: 1865

I would do something like this:

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})`)

Or if you want to extract only one 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')}`)

Upvotes: 0

burkay
burkay

Reputation: 1170

Instead of regex, you can use string split function.

var text = "<!-- Name:Peter Smith --><!-- Age:23 -->"; // Data to be scanned
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;
}

https://jsfiddle.net/ydjbc4yq/

Upvotes: 0

dodov
dodov

Reputation: 5844

This approach returns an object with all the found key/value pairs. From there, you can search for any key you want.

var text = "<!-- Name:Peter Smith --><!-- Age:23 --><!-- Key with  space  : yes -->";

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

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

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

  return data;
}

Upvotes: 0

Related Questions