Using JavaScript, swap out all occurrences of the symbol "*" with elements found in an array

To tackle this problem, I need to create an empty array and then add characters from the provided sentence into it, excluding asterisks. This approach will help me when I eventually need to iterate through the array items for replacements.

function replaceAsterisk(sentence, newWords) {

  let newArray = [];

  let character = sentence.split("");

  console.log(character);

  // If the character is not an asterisk, push it into the new array
  if (character !== "*") {
    newArray.push(character);
  }

  // If the character is an asterisk, push "cat" into the new array
  else {
    newArray.push("cat");
  }
  
  // Return the new array as a string
  return newArray.join(" ");
}

console.log(replaceAsterisk("My name is * and I am a *.", ["Sabrina", "Black Cat", "extra", "words"]));

Despite these instructions, the code still isn't adding "cat" to the array - what could be causing this issue?

Answer №1

Utilize the String.replace() method along with a function that dynamically generates replacement strings. Inside the function, retrieve the current replacement from the array newWords by using a counter:

function replaceAsterisk(sentence, newWords) {
  let counter = 0;
  
  return sentence.replace(/\*/g, () => newWords[counter++] || '');
}

console.log(replaceAsterisk("My name is * and I am a *.", ["Sabrina", "Black Cat", "extra", "words"]));

Answer №2

To start, you must iterate through each individual character before proceeding further. Here is a simple example to illustrate the process:

function replaceAsterisk(sentence, newWords) {

    let newArray = [];

    let characters = sentence.split("");

    console.log(characters);
    
    characters.forEach(function(character){
      // If the character is not an asterisk, add it to the new array
      if (character !== "*") {
        newArray.push(character);
      }

      // If the character is an asterisk, add "cat" to the new array
      else {
        newArray.push("cat");
      }
    });
    // Convert the new array into a string and return it
    return newArray.join("");
}

console.log(replaceAsterisk("My name is * and I am a *.", ["Sabrina", "Black Cat", "extra", "words"]));

Answer №3

To solve this problem, you should iterate through each character in the given sentence:

function replaceAsterisk(sentence, newWords) {
  let newArray = [];

  for( let i = 0; i < sentence.length; i++) { // Ensure all characters are processed
    character = sentence[i];
    // Check if the character is not an asterisk and add it to the new array
    if (character !== "*") {
      newArray.push(character);
    }
  
    // If the character is an asterisk, replace it with "cat" in the new array
    else {
      newArray.push("cat");
    }
  }
  // Convert the new array into a string and return
  return newArray.join(" ");
}

console.log(replaceAsterisk("My name is * and I am a *.", ["Sabrina", "Black Cat", "extra", "words"]));

Answer №4

This solution is effective. It's important to note that splitting on empty strings can behave unexpectedly (refer to MDN...split)

  let newArray = [], sentence = "My name is * and I am a *.";      
  for (let char of sentence){ newArray.push(char); }
  for(let i = 0; i < newArray.length; i++){
    if(newArray[i] == "*"){ newArray[i] = "cat"; }
  }
  console.log(newArray);

Answer №5

utilizing regex group match alongside Array.prototype.shift

updateText = (sentence, replacements) => {
  const _replacements = replacements.slice();
  return sentence.replace(/(\*)/g, (match) => _replacements.shift() || match);
}

// incorporating valid replacements
const updatedSentence1 = updateText("My favorite color is * and I love *.", ["blue", "pizza", "random", "words"]);
console.log(updatedSentence1);

// providing empty replacements
const updatedSentence2 = updateText("My favorite color is * and I love *.", []);
console.log(updatedSentence2);

Answer №6

To accomplish this task, you should iterate through each character in the given sentence and determine the word to substitute with by utilizing the shift method:

function swapPlaceholders(sentence, newWords) {
  let newSentence = "";
  [...sentence].forEach(character => {
    if (character !== "*") {
      newSentence += character;
    } else {
      newSentence += newWords.shift();
    }
  });
  return newSentence;
}

console.log(swapPlaceholders("I have a * and a *.", ["dog", "cat", "parrot"]));

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

Add a jQuery click function within a loop indefinitely

Hello there, I have a simple loop set up in PHP and I am trying to figure out how to create an event that triggers whenever the user clicks on any line generated by this loop. Here's my basic PHP while loop: <?php $x = 1; while($x <= 5) { ...

Update every element of an array containing structures simultaneously using C

I have defined a structure with three variables named var1, var2, and var3 using typedef: typedef struct { int var1; int var2; int var3; } test_t; Next, I have initialized an array of instances of this struct with default values: test_t theTest[ ...

Submitting a form via NextJS to an internal API

After reading through the Next.JS documentation, I came across an interesting point. Note: Instead of using fetch() to call an API route in getStaticProps, it's recommended to directly import the logic from within your API route and make necessary cod ...

Are trailing commas or missing keys acceptable in JavaScript object notation?

I have created a code generator and I am contemplating whether or not to address the issue of the extra comma at the end. While Internet Explorer seems to ignore it, I want to ensure cross-browser compatibility and generate valid code. function init() { v ...

What is the best method for computing the sum of values retrieved in a getter function?

The code below currently prints the following: 21 48 68 96 Instead of printing each individual amount, I want it to just print the total contribution amount, which is 96. How can I achieve this? Here's the code snippet: public int totalContribution( ...

MongoDB does not recognize Db.Collection as a valid function

A lot of people have been inquiring about this specific error, but after thorough investigation, I couldn't pinpoint a similar issue. So I'm reaching out in the hopes that someone might be able to identify and help rectify it. Let me provide som ...

Encountering the error message "{error: 'Operation `users.findOne()` buffering timed out after 10000ms'}" while trying to access my app on localhost

In my project, I have organized my code into 'client' and 'server' folders. The server side of the application is built using Express and successfully connected to a MongoDB database in the server folder using nodemon. https://i.sstati ...

Incorrect credentials trigger an error in Nodemailer

Currently, I am utilizing nodemailer to handle email submissions from a registration form. Below is the code for my registration form: <form action="/registration" method="post"> <h3 class="text-center" style="font-family: 'champagne-l ...

Learn how to showcase a text file uploaded to a webpage with NODE js and HTML

<!DOCTYPE html> <html> <body> <form action = "/submit" method = "post"> Select a file: <input type="file" name="file"> <input type="submit"> </form> </bod ...

Why am I receiving a "Cannot read property 'style' of undefined" error when using the Nanoscroller?

This is the code snippet I've been working on: <ul id="selectProfileOptions_IC" class="dropdownToggle_cont" ></ul> Under this ul element, I have listed some names. To enable scrolling functionality, I employed nanascroller in my project ...

What is the best way to access a parameter from a separate component?

I am utilizing the Graph component provided by react-graph-vis. It allows me to access the graph methods. While I can access the prop (referred to as network in this case) within the function, I am seeking guidance on how to implement actions like trigger ...

Error message occurs when attempting to update a Mongoose document and encounters a TypeError related to the inability to read the property "coordinates"

Attempting my first document update REST api call, not entirely sure if I'm going about it the right way. I aim to have the api call only supply the fields of the document users want to update. My plan was to check for data in each field and add it i ...

Javascript - issue with accurately retrieving element offset value while scrolling

My goal is to dynamically change classes for elements based on their position during scrolling. I am trying to calculate the top offset element value and adjust the classes accordingly. Here is the function I am using: handleScroll () { const header = ...

collecting items and storing them in an array

I am attempting to gather all course codes that have a score below 40 into an array and then display it. However, when I use print_r($carry_over), nothing is returned! $carry_over = array(); while ($row8 = mysql_fetch_assoc($query8)) { if ($row8[&ap ...

Which is better for toggling between images/icons: a switch statement or a ternary operator?

I have a unique challenge where I am dealing with a dynamic list of thumbnails. Some of the items in this list are images, while others need to be represented by icons. My goal is to display either an image or an icon based on the contentType of each item. ...

Harness the power of ng-click in conjunction with data-ng-href for a

I am attempting to create a button that takes the user to the product details while also having the ability to increase a counter using an ng-click function. <div class="row center-block save-button" > <a data-ng-href="/savings/{{saving._id}} ...

Setting up a new folder in the internal storage within a React Native Expo environment

In my React Native Expo project, I am utilizing two functions to store data in a JSON file and then save the file to internal storage. However, the code currently asks for permission to store inside a chosen folder, but does not create the "ProjectName" fo ...

Incorporating Microsoft's Emotion API into an HTML website

Currently, I am attempting to develop a HTML webpage that can detect emotions from images submitted by the user. By referring to Microsoft's documentation, I have produced the following HTML file: <!DOCTYPE html> <html> <head> & ...

Tips for identifying the "index out of bound" error when not encountering a Segmentation Fault

I've encountered an issue with a program that is causing a Segmentation Fault on a machine that I don't have access to. However, when I compile and run the same program using the same compiler and input on my own machine, I am not experiencing an ...

How to eliminate identical values in an array with the help of PHP

I'm looking to display data in an array while excluding any duplicates. Here is a sample of my array: array (size=4) 0 => string 'Eclairage Public' (length=16) 1 => string 'Fonte de Voirie' (length=15) ...