javascriptstringtextareagetelementbyidreplaceall

Can I replace multiple strings with the same variable in Javascript?


This may seem stupid and forgive me if this has been asked a million times no one thread seems to have the answer I'm looking for. I'm very new to coding in general so I very well might just not be comprehending what I'm reading. I have a project I'm working on where I need to be able to replace multiple variations of a name or phrase with one constant word or phrase and I managed to figure it out for a singular one however getting it to work for multiple has failed me for about a day now.

example:

const txtrs = document.getElementById('txt1').value
const replaces = txtrs.replaceAll('variation1', 'proper')
document.getElementById('txt1').value = replaces

which is great but I need it to replace multiple ones however doing

const txtrs = document.getElementById('txt1').value
const replaces = txtrs.replaceAll('variation1', 'variation2' 'proper')
document.getElementById('txt1').value = replaces

doesn't work it just replaces variation1 with variation2 instead of proper as I need and this problem has stumped me because I just can't figure out what I don't understand about it. The HTML it's calling in getElementById is a textarea where users would input whatever they needed to be replaced.


Solution

  • You could use multiple calls chained together:

    const replaces = txtrs
       .replaceAll('variation1', 'proper')
       .replaceAll('variation2', 'proper');
    

    Or use regex:

    const replaces = txtrs.replace(/(variation1|variation2)/g, 'proper');
    

    Or use a loop:

    let replaces = txtrs;
    for (const target of ['variation1', 'variation2']) {
        replaces = replaces.replaceAll(target, 'proper');
    }
    

    Keep in mind that if you choose to use regex, it's a good idea to escape your input in case they have special characters like [, ), $, +, etc.

    Using some answer from Escape string for use in Javascript regex, we could use:

    const replaces = txtrs.replace(
        new RegExp("(" + ['variation1', 'variation2'].map((str) => escapeStringRegexp(str)).join("|") + ")", "g"),
    'proper');
    

    And we'd get the same results.