将两个字符串组合在一起

时间:2018-08-10 17:17:10

标签: javascript regex

我正在尝试将两个字符串组合在一起,但是其中任何重复项都将被替换。 我在想string1会取代string2。

所以,如果我有

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

我想结束:

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

我尝试做:

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

但这最终将第一个字符串替换为第二个字符串。

这可能吗?

1 个答案:

答案 0 :(得分:3)

这可能对您需要的东西有些矫kill过正,但是如果您需要扩展它或处理更多可能性,它应该非常灵活和强大。

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