Rolando
Rolando

Reputation: 62704

Extract specific substring using javascript?

If I have the following string:

mickey mouse WITH friend:goofy WITH pet:pluto

What is the best way in javascript to take that string and extract out all the "key:value" pairs into some object variable? The colon is the separator. Though I may or may not be able to guarantee the WITH will be there.

Upvotes: 0

Views: 101

Answers (5)

Emil A.
Emil A.

Reputation: 3445

You can do it this way for example:

    var myString = "mickey WITH friend:goofy WITH pet:pluto";

    function someName(str, separator) {
        var arr = str.split(" "),
            arr2 = [],
            obj = {};
        for(var i = 0, ilen = arr.length; i < ilen; i++) {
            if ( arr[i].indexOf(separator) !== -1 ) {
              arr2 = arr[i].split(separator);
              obj[arr2[0]] = arr2[1];
            }
        }
        return obj;
    }

    var x = someName(myString, ":");

    console.log(x);

Upvotes: 0

closure
closure

Reputation: 7452

var array = str.match(/\w+\:\w+/g);

Then split each item in array using ":", to get the key value pairs.

Here is the code:

function getObject(str) {
  var ar = str.match(/\w+\:\w+/g);
  var outObj = {};
  for (var i=0; i < ar.length; i++) {
    var item = ar[i];
    var s = item.split(":");
    outObj[s[0]] = s[1];
  }
  return outObj;  
}

Upvotes: 1

LPD
LPD

Reputation: 2883

The string pattern has to be consistent in one or the other way atleast. Use split function of javascript and split by the word that occurs in common(our say space Atleast) Then you need to split each of those by using : as key, and get the required values into an object. Hope that's what you were long for.

Upvotes: 0

Bergi
Bergi

Reputation: 665536

myString.split(/\s+/).reduce(function(map, str) {
    var parts = str.split(":");
    if (parts.length > 1)
        map[parts.shift()] = parts.join(":");
    return map;
}, {});

Upvotes: 1

user160820
user160820

Reputation: 15230

Maybe something like

"mickey WITH friend:goofy WITH pet:pluto".split(":")

it will return the array, then Looping over the array.

Upvotes: 0

Related Questions