简体   繁体   中英

Combining two parts of different strings

am working on a masking field that needs to pre-populate data. I have both sets of data, but don't want to show users the entire number.

I have two bits of information that I need to combine together, but I can't seem to figure out how to do this.

Str1 = XXXXX-XXXXX-XX00
Str2 = 12345-12345-1234

I need to combine these strings so that the user only sees XXXXX-XXXXX-XX34. The pattern (Str1) can be changed so it is not a set in stone pattern which is what is making this difficult.

Is there a way to combine those?

You just need to use use split to make yours strings become arrays and map to filter the final array and finaly join to obtain a String like this :

var  Str1 = "XXXXX-XXXXX-XX00"
var Str2 = "12345-12345-1234"
var result = Str1.split("").map((x, index) => x==='0' ? Str2.split("")[index] : x).join("");
console.log(result); //XXXXX-XXXXX-XX34

A very simplistic approach

 var a = "XXXXX-XXXXX-XX00"; var b = "12345-12345-1234"; var result = ""; if (a.length !== b.length) throw "Strings must be same length."; for (let i = 0 ; i < a.length; i++) { switch (a[i]) { case '0': result += b[i]; break; default: result += a[i]; } } console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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