繁体   English   中英

将两个弦组合在一起

[英]Combine Two strings together

我试图将两个字符串组合在一起,但内部有任何重复项被替换。 我认为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)

但这最终会用第二个字符串替换第一个字符串。

这可能吗?

这可能对你所需要的东西有点过分,但如果你需要扩展它或处理更多的可能性,它应该非常灵活和强大。

 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 = /([az]+) ({.*?})/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)); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM