Javascript continuously swaps out text from distinct strings in a loop

I wrote a loop to split a string and search for certain text to replace it with another string. Here is an example of what I have done:

function replaceStr(str, find, replace) {
  for (var i = 0; i < find.length; i++) {
    str = str.replace(new RegExp(find[i], 'gi'), replace[i]);
  }
  return str;
}

var str = 'some text contain car and some house contain car, or car contain someone';
var values = "cat,dog,chicken";

splt = values.split(',');

for (i = 0; i < splt.length; i++) {
  var find = ['car'];
  var replace = ['' + values[i] + ''];
  replaced = replaceStr(str, find, replace);
}
console.log(replaced);
//console.log(splt.length);

However, the result is returning zeros.

I am trying to locate all instances of "car" in the text and replace them with strings that were separated by commas. Can someone assist me with this issue, please?

Answer №1

What's the objective of your replaceStr function? Perhaps this code snippet accomplishes it:

let str = 'some text contain car and some house contain car, or car contain someone';
let values = "cat,dog,chicken";

const splt = values.split(',');

for (let i = 0; i < splt.length; i++) {
   const find = 'car';
   str = str.replace(find, splt[i]);
}
console.log(str);

Answer №2

It seems like you're looking to dynamically replace the word "car" with different animals in a given text. Here's an example solution for achieving this:

const text = 'some text contain car and some house contain car, or car contain someone';
const animals = "cat,dog,chicken";
const animalArray = animals.split(',');
let replacedText = text;

for (let i = 0; i < animalArray.length; i++) {
  replacedText = replacedText.replace('car', animalArray[i]);  
}

console.log(replacedText);

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

Having trouble iterating through a grouped array in JavaScript?

Regrettably, I am facing issues once again with my grouped messages. Although I have received a lot of assistance from you previously, I still find myself struggling and hesitant to ask for help again. Initially, my objective was to group messages based o ...

How to extract and compare elements from an array using Typescript in Angular 6

I have created a new Angular component with the following code: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HttpClient } from '@angular/common/http'; @Compone ...

The functionality of CSSTransition seems to be malfunctioning. Perhaps switching to V2 of react

Can anyone help me troubleshoot my code snippet where I'm attempting to incorporate an animation for Tooltip Nodes? Despite my efforts, the animation does not show up on the screen after mounting. Additionally, the console.log is not triggered on the ...

Tips on positioning a button "above" the carousel-control-next icon

I have a carousel and I added a button to stop the spinning. However, when I try to click on the button, it seems like the "carousel-control-next" tag is being clicked instead. How can I solve this issue? ** Interestingly, when I remove the "carousel-cont ...

The functionality of AngularJS ng-click is disrupted by the presence of {{$index}}

Having an issue with AngularJS where using $index breaks the ng-click function. This issue arises within a div utilizing ng-repeat, the repeat code is functioning correctly... <a class="accordion-toggle" data-toggle="collapse" data-parent="#acc{{$inde ...

When the input value is changed programmatically, the onchange event does not execute as expected

Having trouble updating the content of my dataTable when using JS script to change the quantity value. Here is a snippet from my code. <h:inputText id="counterFeatures" value="#{myBean.quantity}"> <f:ajax event="change" render="myDataTable" ...

Error: foobar is not defined within this scope (anonymous function)

I'm facing an issue with a JavaScript file hosted on a domain called foobar.com. at http://foobar.com/static/js/main.js: $(document).ready(function() { function foobar(bar){ $.ajax({ url: "/site/foo/", ...

Angularjs does not seem to be rendering content placed within curly braces

I'm working on setting up a page with Angular, and I'm facing an issue with displaying JSON data received from the server. Here is the code snippet: HTML <body ng-app="App"> <nav class="navbar navbar-dark bg-inverse navbar-fixed-top"& ...

Display the hover effect for the current card when the mouse is over it

When the mouse hovers over a card, I want only that specific card to show a hover effect. Currently, when I hover over any card, all of them show the hover effect. Is there a way to achieve this in Vue Nuxtjs? Here's what I am trying to accomplish: ...

Adding additional `select` dynamically causes the value to disappear from view

After attempting to replicate the functionality of the select field, I encountered an issue where it no longer displays any values. Specifically, if I opt for a small size, I encounter this error message in the console. https://i.stack.imgur.com/5hKX6.png ...

Manipulating objects with Jade Mixin

My current challenge involves programmatically displaying objects within a jade template by passing an array of objects to the view. The aim is to present these objects in a grid view with up to 3 items per row. However, I encountered an issue where nested ...

Is there a way to modify the appearance of a particular element in ng-repeat?

On my website, I am using ng-repeat to display various dish postings. I want to trigger a modal to open when I click on a dish, showing the specific data for that dish. To achieve this, I'm assigning each dish a modal div with a unique ID (dish-$index ...

Changing the color of an Angular <div> element with scripting

I am currently working on an Angular 6 project and I need to change the colors of a div tag from a script after a click function. However, I also need to change it back to transparent. When I click on the "Inheritance" option, the background color of the ...

Navigating Through Secondary Navigation with Ease

In my React project, I am developing a mega-menu styled dropdown navigation. As a functional component, I am utilizing the useState hook to manage the state and control the display of sub-navigation items. The functionality of the dropdown is operational, ...

Solving the problem of Axis label alignment in Three.js grid and techniques for visualizing x, y, z data on

I have been tasked with plotting well deviation surveys on a 3D grid. After referencing several articles online, I successfully created a 3D grid of the required size. However, I am currently struggling with positioning the labels for the x, y, and z axis ...

Import a JSON file into Parse by reading and parsing it to store in the database

I am currently facing a challenge with parsing JSON data in my Parse Cloud function. After fetching the JSON file, I need to parse the data and populate one of my classes with the results. However, I'm having trouble figuring out how to properly parse ...

Displaying Values/Marks in a Unique Order with Material-UI Slider Component

The default behavior of the Material-UI slider is to display marks/values in ascending order from min to max For instance, if you have a slider configured like this: const marks = [ { value: 1, label: '1' }, { value: 2, lab ...

The 'length' cannot be searched using the 'in' operator

I am experiencing an issue that I can't quite solve. I have come across solutions for this problem, but they all involve methods that don't use AJAX to retrieve data. If anyone can assist me with this, I would greatly appreciate it. Here is the J ...

Issue with Angular 13 Bootstrap5 Navbar's functionality

Angular 13 is my framework of choice, and I recently integrated Bootstrap 5 into my project using the command below: ng add @ng-bootstrap/ng-bootstrap As for the index.js file content, it looks like this: <!doctype html> <html lang="en" ...

How to efficiently retrieve a form's data from multiple forms with identical ids in JavaScript

I am facing a challenge with multiple forms on the html page that have the same ID. I need to send each form's information to the server based on user selection, but I haven't been able to find a relevant solution. For my Authorization polic ...