0

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);
4
  • john should be a name of variable of array or what? Commented Jan 2, 2020 at 19:57
  • 3
    Show us what you have tried so far. Commented Jan 2, 2020 at 19:59
  • @DominikMatis yea, john is the name of the variable of which the string 'the quick brown' is associated to Commented Jan 2, 2020 at 20:03
  • @Taplar it isnt much, but i have updated my original post Commented Jan 2, 2020 at 20:03

4 Answers 4

2

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))

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

3 Comments

is there a way to make the variable names seperate from the message? like john: "the quick brown"
You can use JSON instead of array then.
@Mosukoshide - I have updated my answer to turn the array into a JS object with names as variables
1

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"])

Comments

0

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

1 Comment

is there a way to make the variable names seperate from the message? like john: "the quick brown" so that I can do console.log(result["john"]);
0
  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;
        }, {})
    );
    

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.