Search code examples
regexscriptlet

Replace every nth instance of a character using RegEx


I have a pipe delimited string of values looking something like below:

s1 | s2 | s3 | s4 | s5 | s6 | s7 | s8 | s9 | s10 | s11 | s12 | s13 | s14 | s15 | s16 | s17 | s18 | s19

What I want to do is to replace every sixth instance of | with a ; so that I have something like this..

s1 | s2 | s3 | s4 | s5 | s6 ; s7 | s8 | s9 | s10 | s11 | s12 ; s13 | s14 | s15 | s16 | s17 | s18 ; s19

I manage to get every second Pipe replace by using code below, but no luck with every sixth pipe.

"s1 | s2 | s3 | s4 | s5 | s6 | s7 | s8 | s9 | s10 | s11 | s12 

**".replace(/\|([^|]*)\|/g, '|$1:')**

Any advice would be greatly appreciated.


Solution

  • I wouldn't use a regex for this. Instead you can split on | and work based off of the index to do string building. In JavaScript:

    string.split("|").reduce((prev, next, id) => prev + (id % 6 ? "|" : ";") + next);
    

    If you must use a regex, you can look for this pattern 6 times and replace everything between it:

    string.replace(/(.*?\|.*?\|.*?\|.*?\|.*?\|.*?)\|/g, "$1;")