Search code examples
google-sheetsgoogle-sheets-formulaarray-formulasregexp-replacegs-vlookup

How does one replace a character at N positions in a string in a cell in Google Sheets


I have a long string of characters in a cell A1:

sdfhgt9|ft8yy|1gftre|78hedd

In cell A2 I have a set of comma-separated numbers to indicate the positions for replacing the character within the cell:

4,10,19,26

The characters at these positions have to be replaced by a "#", so the output should look like:

sdf#gt9|f#8yy|1gft#e|78he#d

I tried using the replace function with an arrayformula.

=ARRAYFORMULA(replace(A1,split(A2,","),1,"#"))

creates these 4 different strings in A3,A4,A5,A6:

sdf#gt9|ft8yy|1gftre|78hedd 
sdfhgt9|f#8yy|1gftre|78hedd  
sdfhgt9|ft8yy|1gft#e|78hedd 
sdfhgt9|ft8yy|1gftre|78he#d

I am now not able to join and build one string with all 4 "#" replacements.

I am looking at solving this with the regular functions in Sheets, no custom coding.


Solution

  • See if this works

    =regexreplace(A1, "^(.{3}).(.{5}).(.{8}).(.{6}).", "$1#$2#$3#$4#")
    

    Or, if you want to use the contents of cell A2

    =join("",ArrayFormula(if(regexmatch(row(indirect("A1:A"&len(A1)))&"", "\b"&SUBSTITUTE(A2, ",", "|")&"\b"), "#", transpose(split(regexreplace(A1, "(.)", "$1-"), "-")))))