1

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!

1
  • Here's an example how to create a Regex that support similar data format: regex101.com/r/euwxBp/1 Since you're in JavaScript land, I'd convert the data to to an object, for its native key-value support, and then lookup 'keys' by getting the obj[key] ref and checking if it exists. P.S. - You haven't mentioned what key and data formats should be supported - so the Regex is pretty basic. Commented Feb 26, 2017 at 9:13

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

Comments

0

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/

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.