Node js Separate String into arrays

43 views Asked by At

Got a String which look like this

-FirstName (Some Random Name) -LastName (Some Random Last Name) -Age 30

I'm looking for the best and easiest way to extract the First name Last name and Age from this string. So i can store this Data in a Database.

The order of the tags can be random.

2

There are 2 answers

0
zmii On BEST ANSWER

UPDATED ANSWER

As I remember indexOf is faster the regular expressions. So this is the answer for your question:

var a, i, flags, result, flag, entry, start, end;

a = "-FirstName Some Random Name -LastName Some Random Last Name -Age 30"

flags = ["-FirstName", "-LastName", "-Age"];
result = [];
for (i = 0; i < flags.length; i++) {
    flag = flags[i];
    entry = a.search(flag);
    lookup_start = entry + flag.length;

    end = a.indexOf("-", lookup_start);
    end = (end == -1) ? a.length : end;
    result.push(a.slice(lookup_start, end).trim())
}

console.log(a);
console.log(result);

Now you will have a mapping - flags[i] -> result[i]. So you can build up an object for example easily.

0
halbgut On

It's easiest to use regex. The Problem is that there can be dashes and spaces in names. So I'd try something like this:

var tags = []

'-FirstName Some Random Name -LastName Some Random Last Name -Age 30'.replace(/\-([\w]{3,9})\s?((\w|\s|(\w\-))+)?\s?/gm, function () {
  tags.push(arguments)
  return ''
})

console.log(tags)