0

I have example string:

[:pl]Field_value_in_PL[:en]Field_value_in_EN[:]

And I want get something like it:

Object {
    pl: "Field_value_in_PL",
    en: "Field_value_in_EN"
}

But I cannot assume there will be always "[:pl]" and "[:en]" in input string. There can by only :pl or :en, :de and :fr or any other combination.

I tried to write Regexp for this but I failed.

1
  • don't get discouraged, try again! Commented Feb 26, 2016 at 18:01

3 Answers 3

2

Try using .match() with RegExp /:(\w{2})/g to match : followed by two alphanumeric characters, .map() to iterate results returned from .match(), String.prototype.slice() to remove : from results, .split() with RegExp /\[:\w{2}\]|\[:\]|:\w{2}/ to remove [, ] characters and matched : followed by two alphanumeric characters, .filter() with Boolean as parameter to remove empty string from array returned by .split(), use index of .map() to set value of object, return object

var str = "[:pl]Field_value_in_PL[:en]Field_value_in_EN[:]:deField_value_in_DE";

var props = str.match(/:(\w{2})/g).map(function(val, index) {
  var obj = {}
  , prop = val.slice(1)
  ,vals = str.split(/\[:\w{2}\]|\[:\]|:\w{2}/).filter(Boolean);
  obj[prop] = vals[index];
  return obj
});

console.log(JSON.stringify(props, null, 2))

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

Comments

1

Solution with String.replace , String.split and Array.forEach functions:

var str = "[:pl]Field_value_in_PL[:en]Field_value_in_EN[:fr]Field_value_in_FR[:de]Field_value_in_DE[:]",
    obj = {},
    fragment = "";

var matches = str.replace(/\[:(\w+?)\]([a-zA-Z_]+)/gi, "$1/$2|").split('|');
matches.forEach(function(v){    // iterating through key/value pairs
    fragment = v.split("/");
    if (fragment.length == 2) obj[fragment[0]] = fragment[1];  // making sure that we have a proper 'final' key/value pair
});

console.log(obj);
// the output:
Object { pl: "Field_value_in_PL", en: "Field_value_in_EN", fr: "Field_value_in_FR", de: "Field_value_in_DE" }

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

Comments

0

You can try this regex to capture in one group what's inside a pair of brackets and in the other group the group of words that follow the brackets.

(\[.*?\])(\w+)

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.