Switch out arbitrary segments of text in JavaScript

I am attempting to replace a randomly selected substring within a string with another substring. Below is the code I am using:

function replaceRandomSubstring(str, substr, repl) {
  var amount = str.match(substr);
  var newstr = str;
  if (amount.length != -1) {
    var index = Math.floor(Math.random() * amount.length);
    var i = 0;
    do {
      if (i == index) newstr = newstr.replace(substr, repl);
      else newstr = newstr.replace(substr, "placeholder");
      i++;
    }
    while (i < index);
    newstr = newstr.split("placeholder").join(substr);
  }
  return newstr;
}

The issue I'm facing is that it only replaces the very first occurrence of the substring, not a random one as intended.

Answer №1

The reason for this behavior is that the amount function does not return all occurrences of the substrings in a string. It only returns the first match found.

An alternative solution is to utilize the String.prototype.matchAll() method:

function replaceRandomSubstring(str, substr, repl) {
  const amount = [...str.matchAll(substr)]; // gathering all substring matches in an array

  if (amount.length !== -1) {
    const index = Math.floor(Math.random() * amount.length);

    let i = 0;

    do {
      if (i === index) str = str.replace(substr, repl);
      else str = str.replace(substr, 'placeholder');
      i++;
    } while (i <= index);

    str = str.split('placeholder').join(substr);
  }
  return str;
}

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

Refreshing the page resolves unhandled errors that occur when an item is removed from local storage

I'm currently working on adding a logout button to my website. I have the user's token saved in local storage, but when the logout button is clicked and the token is removed from local storage, an error occurs upon redirecting back to the login p ...

What is the best way to form a singular entity and insert numerous sets of key-value pairs within it?

Currently, I am working on creating an object that contains multiple key-pair values obtained from an API response. My goal is to transform the API response into a single object, but the code I have written does not produce the desired result. This is my ...

Checkbox in Meteor always returns false after the template has been rendered

I've created a navigation bar with 2 options. One option is a checkbox and the other is a dropdown with a button (code provided below). The checkbox has the ID "inputMode" and the button has the ID "addNewObject" <div class="collapse navbar-colla ...

Deliver an extensive JSON reply through a Node.js Express API

When dealing with a controller in a node/express API that generates large data sets for reports, reaching sizes as big as 20Mb per request, maintaining a positive user experience becomes essential. What strategies can be employed to efficiently handle suc ...

A code snippet designed to ensure uniform height for all floating div elements

Hello, I am facing an issue with resizing 20 left-floated divs of varying heights on my website. Previously, when my website was designed using pixels, a script worked perfectly for resizing them. However, after switching to a percentage-based design (% d ...

What is the best way to combine elements in an array of strings using commas between each item, but using "and" before the last item?

I have a collection of phrases that looks like this. ['white t-shirt', 'blue jeans', 'red hat', 'brown glasses'...] I am looking for a way to insert these phrases into the text below, separated by commas, with the w ...

Error: Google Chrome encountered an unexpected token } that caused a syntax error

I encountered an error that reads: Uncaught SyntaxError: Unexpected token } This error only appears in Chrome, while other browsers like Mozilla and IE do not show it. Here is my script causing the issue: <script type="text/javascript" language="jav ...

Creating a delayed queue using RxJS Observables can provide a powerful and

Imagine we have a line of true or false statements (we're not using a complicated data structure because we only want to store the order). Statements can be added to the line at any time and pace. An observer will remove items from this line and make ...

Iterate over the array and eliminate any stylesheets

Currently working on a website using WordPress, and dealing with some unwanted css files that come with certain plugins. I've been attempting to remove these stylesheets with JavaScript but keep running into an error saying Failed to execute 'qu ...

Tips for positioning the footer in HTML and CSS

footer { background-color: #000000 } .footer-nav { list-style: none; } .footer-nav li { display: inline-block; margin: 15px; font-weight: 400; font-size: 80% } .social { list-style: none; } .social li { display ...

When calling a method that has been created within a loop, it will always execute the last method of the

In my project, I am utilizing node version 0.8.8 in conjunction with express version 3.0. Within the codebase, there exists an object named checks, which contains various methods. Additionally, there is an empty object called middleware that needs to be p ...

Unable to pass value through form submission

Having some trouble displaying data from an API on my HTML page. The function works fine when I run it in the console. <body> <div> <form> <input type="text" id="search" placeholder="Enter person& ...

Automatically populate form fields with data from the clicked row in the HTML table when using JSP

Attempting to populate form fields using jQuery or JavaScript with row elements selected by clicking on the row. Tried a solution from Stack Overflow that didn't work as expected. I'm new to this, so please bear with me. (http://jsbin.com/rotuni/ ...

The callback for closing the $uibModal with a value will consistently result in undefined

Using ng-click="$widget.addItem()" in my template triggers a $uibModal. Everything is functioning properly - opening, closing, etc. The issue arises when trying to get the callback value from $modal.close($value). The function itself works correctly, the ...

What benefits does the useCallback() hook offer in addressing function equality concerns within React?

Exploring useCallback() Hook In my quest to grasp the inner workings of the useCallback() hook in React and its significance in resolving function equality concerns, I came across a blog post shedding light on the topic. However, there are still some aspe ...

The function socket.on(..) is not being triggered

Currently, I am in the process of developing a straightforward website to showcase socket communication and chat capabilities. The server side is coded using Python Flask app, while the client-side utilizes JavaScript. Below is an excerpt from the server c ...

Is there a way to apply styles to a checkbox's child element depending on the checkbox's state without relying on ternary operators within Styled Components?

I am currently working on styling this component using Styled Components, but I feel like my current approach is a bit of a hack. What would be the best practice for incorporating Styled Components to style this component effectively? If I were to use Pla ...

Encountering a "Module not found" error while trying to run npm start in a Create React App

I'm attempting to initiate a React project using create-react-app. Encountered an error when running npm start: Failed to compile. multi ./node_modules/react-scripts/config/polyfills.js ./node_modules/react-dev-utils/webpackHotDevClient.js ./src/i ...

Challenges and solutions in writing Protractor test cases

Recently delving into protractor e2e testing, I have developed my first test code. Seeking feedback and suggestions for improvement. describe("Map feedback Automation",function(){ it("Check if the Url works ",function() { browser.get(browser.params. ...

I am attempting to display films within a watchlist module, however it is not allowing me to do so

I have developed a small movie database and need to showcase movies on my watchlist. While I am able to search for movies, adding them to my watchlist is only reflected in the Homescreen component and not in the WatchList component. This is the current s ...