Replace word A with word B

Words = {
  "banana":"Lion",
  "apple":"Dog",
};

var string = "banana apple";

How do i make it so that, “banana” is replaced by “Lion”, and “apple” is replaced by “Dog”, case-insensitive in JS?

I also want it so that if new words are added to the “Words” array, they will also be replaced if found in the String variable.

var string = Words["banana"] + " " + Words["apple"];

Use Object.entries to get a list of pairs of items and then run a forEach with the string’s replace method on it make sure to use a regex because I think it only replaces one instance of the word if you just striahgt up pass a string. I’d also really advise against naming a string string, I’ll assume you’re doing that just for the example

3 Likes

I want to replace them without knowing which words are which, i want it to automatically detect it.

I don’t really have time to code it, because i’m in a rush.
That’s why i asked in this forum, so someone can code it for me.

The way you’d do what @javaarchive suggested is something like this, with lots of comments so you can actually learn something from it:

const wordReplaces ={
  apple: 'lion',
  banana: 'dog'
};
let string = "apple is a banana";
Object.keys(wordReplaces) // get the keys of the words as an array i.e. ["apple", "banana"]
  .forEach( // loop over the keys
    key => {
      let wordRegex = new RegExp(`\b${key}\b`, "gi"); // \b is a word boundary so we don't replace things in the middle of words - remove those if you'd like. The "gi" means to search globally and case-insensitively
      string.replaceAll(wordRegex, wordReplaces[key]); // replace every occurence of the word with the new word
    })

Then just run that for whatever you want :slight_smile:

2 Likes

Thank you so much!

Edit: Uncaught reference error, regex isn’t defined?

You can do it without Regex class. Simply Like this:

let wordRegex = /SomeRegex^/;
....

In this case the map keys are strings unfortunately you’ll need the regex class to change it into a regex object
Example:

new RegExp(`${key}`, "gi");

mostly a correction of pufferfish’s code

3 Likes

nevermind i’ll just do each word manually.

var replaced = original.replace("1", "2");
var replaced = original.replace("3", "4");
var replaced = original.replace("5", "6");
1 Like

That won’t quite work, because you can’t re-declare replaced and also because each time you’re going back to the original to do the substitution whereas you want all of the substitutions to be … cumulative:

var replaced = original.replace("1", "2");
replaced = replaced.replace("3", "4");
replaced = replaced.replace("5", "6");

hth

4 Likes

Yea i also figured that out lol