Swap all occurrences of an array within a given string with a different array

I'm currently developing a JavaScript applet that involves replacing array entries in a given string with elements from another array. Here is the code I have so far:

const str = "Lion, Unicorn, Unicorn";
const arr1 = ["Lion", "Unicorn"]; 
const arr2 = ["Fox", "Hound"];
const newStr = str.replaceAll(arr1[0], arr2[0]) //returns "Fox, Unicorn, Unicorn"

The output I want to achieve is: Fox, Hound, Hound. I am looking to create a function that repeats this process for each item in an array, but I'm unsure of how to proceed.

Thank you!

Answer №1

Is this the solution you were thinking of? I hope I grasped the question correctly.

You could implement a recursive function like so:

let sentence = "Lion, Unicorn, Unicorn";
let wordsToReplace = ["Lion", "Unicorn"]; 
let replacementWords = ["Fox", "Hound"];

function replaceWords(str, toReplace, replacements) {
  let word = toReplace.shift(); // toReplace[0] - if array change is important
  let replacement = replacements.shift(); // replacements[0] - if array change is important
  if (!word || !replacement) return str;
  str = str.replaceAll(word, replacement );
  return replaceWords(str, toReplace, replacements); // return replaceWords(str, toReplace.slice(1), replacements.slice(1)) - if array change is important
}

console.log(
  replaceWords(sentence, wordsToReplace, replacementWords)
)

Answer №2

It can be beneficial to start by converting the inputs into a more manageable format. In this particular scenario, viewing the input sentence as an array of words and combining the two replacement arrays into a single mapping object provides greater clarity...

let string = "Lion, Unicorn, Unicorn";
let array1 = ["Lion", "Unicorn"]; 
let array2 = ["Fox", "Hound"];

// manipulate the inputs
let input = string.split(", ");
let translator = array1.reduce((acc, key, i) => {
  acc[key] = array2[i];
  return acc;
}, {});

// now input is ['Lion', 'Unicorn', ...]
// and transator is { 'Lion' : 'Fox', ... }

// solving the issue is now simply a matter of using a couple of lines of code to map the input over the translator
let output = input.map(e => translator[e] || e)
console.log(output.join(", "))

Answer №3

To transform the string into an array of individual words, we utilize the split(', ') method and then use map() to swap them out by searching for a match with indexOf():

Please refer to the code comments. A concise one-liner solution can be found at the conclusion.

const sentence = "Lion, Unicorn, Unicorn";
const arr1 = ["Lion", "Unicorn"]; 
const arr2 = ["Fox", "Hound"];

// Separate based on ', '
let separated = sentence.split(', ');

// Map function
let outcome = separated.map(word => {

  // Locate position in arr1
  const index = arr1.indexOf(word);
  
  // Replacement if found
  if (index !== -1) {
  
      // Return substitute
      return arr2[index];
  } else {
      
      // Return original
      return word;
  }
});

// Form new string
outcome = outcome.join(', ');

// Display result
console.log(outcome);

// Alternatively, as a one-liner
let outcome2 = sentence.split(', ').map(word => (arr1.indexOf(word) !== -1) ? arr2[arr1.indexOf(word)] : word).join(', ');
console.log(outcome2);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to Wrapping Inner or Wrapping All Elements Except for the Initial Div Class

I am looking to enclose all the elements below "name portlet-title" without including other elements within the "div class name portlet-title". I have attempted the following methods: 1) $("div.item").wrapAll('<div class="portlet-body"></div ...

Full-screen modal fade not functioning properly

I am trying to implement multiple fullscreen modals on a single page, but I am facing an issue where they slide in and out at an angle instead of just fading in and out. I have been unable to achieve the desired effect of a simple fade transition. If you ...

What is the best way to iterate through a string array multiple times in C#?

Struggling to find a way to iterate through a string array multiple times after the initial loop has been completed. Current code snippet: string[] assignments = new string[] {"A", "B", "C", "D", "E", "F"}; Array.Resize<string>(ref assignm ...

The directly stored array supplied by the user is stored

I came across this discussion on Stack Overflow regarding the topic of Security - Array is stored directly. Here is a snippet of my code: public IndexBlockAdapter(String[] itemStr) { if(itemStr == null) { this.itemStr = new String[0]; } ...

What is the best way to dynamically adjust the select option?

I need help with handling JSON objects: [ { id: "IYQss7JM8LS4lXHV6twn", address: "US", orderStatus: "On the way", }, ]; My goal is to create a select option for the order status. If the current status is "On ...

Conceal the .dropdown-backdrop from bootstrap using solely CSS styling techniques

Is there a way to hide the .dropdown-backdrop element from Bootstrap for a specific dropdown on a webpage using only CSS? I found a solution that involves Javascript, you can view it on JSFiddle here. However, I am hoping to achieve this without relying o ...

Revolutionary custom binding with Bootstrap popover integration

Utilizing asp.net mvc with dynamic knockout columns, I am facing an issue with one of the column headers named "Status". The desired functionality includes a bootstrap popover that displays information when a user clicks a font-icon question mark. Here is ...

Using an outdated version of Node.js to set up a React App

Attempting to utilize Create React App but encountering an issue that demands Node 10 or above. Presently, my node version is Node 8.10.0 and unfortunately, I am unable to update the Node version as it's a work device. Is there a method to operate an ...

What is the best way to utilize a component function within Vue to delete an item from an array stored in the parent's data?

It might be more helpful for you to take a look at the VueJS code related to this and then I can provide some explanation: new Vue({ el: '#app', data: { history: [ {name: 'red', value: '#f00'}, ...

Determining the size of an element in AngularJS without relying on a function

Here is the HTML content I am working with: <span>{{queries['q1_name'].parameters.length}}</span> <!--Not working: Doesn't show length of parameters--> Below is my JavaScript object: $scope.queries = {"q1_name": ...

Transform numpy array using minimal scaling ratio

I have an array that is not following a consistent increasing pattern. I want to transform it into a consistently increasing sequence by applying a fixed rate whenever the values in the array decrease. Below is a brief example demonstrating this concept w ...

In TypeScript, how does "number" differ from "Number"?

Within the realm of TypeScript, there exist two distinct variations of the "number" type. The first is denoted as lowercase number, whereas the second is represented in uppercase as Number. Attempting to display number results in a compiler error: console. ...

Update the DIV using instructions sent from the server

Looking to create a webpage that retrieves data from a mySQL database, specifically a value of 0 or 1. The goal is to have a div on the page automatically refresh with the latest value from the database at set intervals. Additionally, it's important ...

Is there a way to achieve results similar to CakePHP's INNER JOIN using only PDO?

Looking to retrieve data using INNER JOIN and PDO in a query. How can CakePHP achieve the same? SELECT * FROM users INNER JOIN group ON users.group_id = group.id When using CakePHP, the array structure will look like this: Array Users |-- id |-- name |- ...

Issue obtaining information from Firestore and presenting it visually on the screen

I have been working on developing a website using Angular and Firebase. The site allows different users to create accounts, and registered users can add contacts to the Firestore database. However, I have encountered a problem where the added contact info ...

Shutting down browser with WebdriverIO and launching a new one

I am facing a challenge in my application testing process. I need to simulate a scenario where I close the browser and session, then open a new browser and session to check if the previously entered data can be successfully recalled by passing certain laun ...

Html.BeginForm does not offer onBegin or onComplete methods similar to Ajax.BeginForm

I am currently working with ASP.NET MVC 5 and have implemented a loader during form submission using Ajax.BeginForm: @using (Ajax.BeginForm("Filter", "Log", new AjaxOptions() { OnSuccess = "reloadGrid", OnFailure = "notifyError", HttpMethod = "POST", Load ...

The code snippet `document.getElementById("<%= errorIcon.ClientID %>");` is returning a null value

I need to set up validation for both the server and client sides on my registration page. I want a JavaScript function to be called when my TextBox control loses focus (onBlur). Code in the aspx page <div id="nameDiv"> <asp:Upd ...

Vanishing message when clicked in PHP

I created a code to display error messages and success messages based on user input, allowing them to click anywhere on the screen to dismiss the message. The issue I am facing is that when the user receives both a success and an error message simultaneo ...

What is the best way to thoroughly uninstall Ionic and Cordova from an Ubuntu system?

Is there a way to completely remove Cordova and Ionic 1 and all of their dependencies from my Ubuntu system? And how can I reinstall them again? I found this blog helpful for installing Ionic and its dependencies: I attempted to uninstall Cordova and Ion ...