Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
Switch characters progressively to another in a string

How can I replace all caracteres by another with all possibilities ?

The function switch progressively all the characters by another.

const globalReplace = (chain) => {
    let d = 0;
    for (let i = 0; i <= chain.length - 1; i++) {
        for (let j = 0; j <= d; j++) {
            console.log(chain.slice(0, chain.length - 1 - i), 'X', chain.slice(chain.length - i, chain.length + 1));
        }
        d++;
    }
    return;
};

globalReplace('ABCDE');

the result is :

ABCDX ABCXE ABCXE ABXDE ABXDE ABXDE AXCDE AXCDE AXCDE AXCDE XBCDE XBCDE XBCDE XBCDE XBCDE

but i would like :

ABCDX ABCXE ABCXX ABXDE ABXXE ABXXX AXCDE AXXDE AXXXE AXXXX XBCDE XXCDE XXXDE XXXXE XXXXX

Have you any ideas ? I think my function is close to the result.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

As you mentioned, order of output strings is not important. Keeping that in mind, I've written a code in python (I'm not well versed with js). You can translate it as you need.

def global_replace(chain, r_chr): # chain is the string to replace, r_chr is character (in your example, 'X')
    replaced_strings = []
    for i in range(0, len(chain)):
        r_str = r_chr * (i+1)          # this creates a replace str of length (i+1) with repeated r_chr
        for j in range(0, len(chain)-i):
            s = chain[:j] + r_str      # slice and replace portion of "chain" with r_str
            if j+i+1 < len(chain):     # string index error check
                s += chain[j+i+1:]
            replaced_strings.append(s)
    return replaced_strings 
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!