Mosukoshide
Mosukoshide

Reputation: 61

How to split string and organize in array?

I am trying to separate these string:

var str = '(john) the quick brown (emily) fox jumps over (steam) the lazy dog.'
var str1 = '(john) the quick brown fox jumps over (steam) the lazy dog.'

so that the array will look something like this:

     john: "the quick brown"
     emily: "fox jumps over"
     steam: "the lazy dog."

and

     john: "the quick brown fox jumps over"
     steam: "the lazy dog."

So far I have tried to use the split() and join() functions, but to no avail.

var strNew = str.split(' ').join('|');
var johnSplit = strNew.split('(john)');
str = johnSplit;
var emilySplit = str1.split('(emily)');
console.log(johnSplit);
console.log(emilySplit);

Upvotes: 0

Views: 84

Answers (4)

spender
spender

Reputation: 120450

You can do this quite neatly with a regex, a generator function and Object.fromEntries

function* split(str) {
  const regex = /\((.*?)\)\s*(.*?)(?=\s*(\(|$))/gm;
  let m;
  while ((m = regex.exec(str)) !== null) {
    yield [m[1], m[2]]
  }
}

const str = `(john) the quick brown (emily) fox jumps over (steam) the lazy dog.`;
const output = Object.fromEntries(split(str))

console.log(output)
console.log(output["john"])

Upvotes: 1

Nikhil Goyal
Nikhil Goyal

Reputation: 1973

Try the below method.

var str = '(john) the quick brown (emily) fox jumps over (steam) the lazy dog.'
var str1 = '(john) the quick brown fox jumps over (steam) the lazy dog.'

function splitAndCreateArray(str) {
    return str.split('(').filter(s => !!s).map(s => s.replace(')', ':'));
}

console.log(splitAndCreateArray(str))

If you want your answer to be in JSON, please use the below snippet.

var str = '(john) the quick brown (emily) fox jumps over (steam) the lazy dog.'
var str1 = '(john) the quick brown fox jumps over (steam) the lazy dog.'

function splitAndCreateArray(str) {
return str.split('(').filter(s => !!s).reduce((acc, curr) => {
    const [key, value] = curr.split(')');
    acc[key] = value; // Optional: You can use value.trim() to remove the white spaces.
    return acc;
}, {});
}

console.log(splitAndCreateArray(str))

Upvotes: 2

Kalman
Kalman

Reputation: 8121

  1. Split string into array with ( elements
  2. Remove empty elements
  3. Use reduce to turn array into JS object
  4. Extract variable name using Regular Expression Capture Group

    const str = '(john) the quick brown fox jumps over (steam) the lazy dog.';
    console.log(
      str
        .split('(')
        .filter(elem => elem)
        .reduce((accum, curr) => {
          const varNameRegex = new RegExp(/(.*)\)/);
          const varName = curr.match(varNameRegex)[1];
          accum[varName] = curr.replace(varNameRegex, '').substring(1);
    
          return accum;
        }, {})
    );
    

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386610

You could split by parentheses and reduce the parts.

var string = '(john) the quick brown (emily) fox jumps over (steam) the lazy dog.',
    result = string
        .split(/[()]/)
        .slice(1)
        .reduce((r, s, i, a) => {
            if (i % 2) r[a[i - 1]] = s.trim();
            return r;
        }, {});

console.log(result);

Upvotes: 0

Related Questions