adventcloud
adventcloud

Reputation: 41

Combine Two strings together

I am trying to combine two strings together, but have any duplicates inside be replaces. I'm thinking string1 would supersede string2.

So if I have:

str1 = 'user { id name } roles { id name }';
str2 = 'user { roles match } permissions { id role_id }';

I would like to end up with:

'user { roles match } roles { id name } permissions { id role_id }'

I tried doing:

str1.replace(/[a-z]* {.*}/g, str2)

But this ends up replacing the first string with the second string.

Is this possible to do?

Upvotes: 1

Views: 116

Answers (1)

sbrass
sbrass

Reputation: 995

This might be a little overkill for what you need, but it should be pretty flexible and robust if you need to extend it or handle more possibilities.

str1 = 'user { id name } roles { id name }';
str2 = 'user { roles match } permissions { id role_id }';

//Return an object containing the key and object parts of a string
//getParts(str1) -> {user: '{ id name }', roles: '{ id name }'}
function getParts(s) {
  var out = {};
  var re = /([a-z]+) ({.*?})/gi;
  match = re.exec(s);
  while (match) {
    out[match[1]] = match[2];
    match = re.exec(s);
  }
  return out;
}

//Takes in the parts object created by getParts and returns a space
//separated string. Exclude is an array of strings to exclude from the result.
//makeString(getParts(str1), ['user']) -> 'roles {id name}'
function makeString(parts, exclude) {
  if (typeof exclude === 'undefined') {
    exclude = [];
  }
  var out = [];
  for (var key in parts) {
    if (!parts.hasOwnProperty(key)) {
      continue;
    }
    if (exclude.indexOf(key) !== -1) {
      continue;
    }
    out.push(key + ' ' + parts[key]);
  }
  return out.join(' ');
}

//Combines two strings in the desired format, with s2 keys taking precedence
//in case of any duplicates
function combine(s1, s2) {
  var p1 = getParts(s1);
  var p2 = getParts(s2);
  return makeString(p1, Object.keys(p2)) + ' ' + makeString(p2);
}

console.log(combine(str1, str2));

Upvotes: 3

Related Questions