Here is a helpful guide on using the replace() function in JavaScript to swap out specific words within a text that match

My task involves manipulating the following text:

const a: string = 'I like orange, blue, black, pink, rose, yellow, white, black';

Along with this string:

const b: string =['black', 'yellow'];

The objective is to replace all instances of black and yellow in string a with violet. Thus, the final result should appear as follows on the screen:

'I like orange, blue, violet, pink, rose, violet, white, violet'.

I am aware of the replace() function but I am unsure how to use b as an argument. Can someone provide guidance?

If possible, I would also like to implement an input field for the replacement colors instead of hardcoded values. This way, I could dynamically type any desired color into the text. Thank you for your assistance!

Answer №1

To find and replace multiple words in a given string, you can create a regular expression using the array of words joined by the OR sign (|).

let sentence = 'I like orange, blue, black, pink, rose, yellow, white, black';
const wordsToReplace = ['black', 'yellow'];
   
sentence = sentence.replace(new RegExp(wordsToReplace.join('|'), 'g'), 'violet');

console.log(sentence);

Here is an example with input:

function changeText() {
    document.getElementById('output').innerHTML = 
        sentence.replace(new RegExp(wordsToReplace.join('|'), 'g'), document.getElementById('input').value);
}

let sentence = 'I like orange, blue, black, pink, rose, yellow, white, black';
const wordsToReplace = ['black', 'yellow'];
<input id="input" type="text" value="" onchange="changeText();" />
<div id="output"></div>

Answer №2

replace() does not support arrays as input. However, there is a workaround solution available. One approach is to iterate over each word that needs to be replaced in the string.

let originalString: string = 'I enjoy seeing red, green, blue and yellow colors'

const wordsToReplace: string[] = ['green', 'yellow']

wordsToReplace.forEach(word => {
    originalString = originalString.replace(word, 'purple')
})

Additionally, it's worth noting that const variables are immutable. To have a variable that can be modified, consider using let.

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

Is it possible to incorporate a timer script like chrontab within an Apache setting?

Is it possible to create a chronTab that runs a php script on an Apache web server (Unix based systems) in conjunction with the Node.js server-side program? My goal is to use this to check if a browser is still active and when to end sessions. The chronTa ...

What is the process for expanding types for a section element in Typescript?

When working with TypeScript, we define our component props types by extending a div like so: import { HTMLAttributes } from "react"; export interface IContainerProps extends HTMLAttributes<HTMLDivElement> { // Additional custom props for the c ...

Resolving TypeError: matchesSelector method is not recognized within React component

I am currently integrating masonry-layout from the official website to create a masonry grid within my component. However, I encountered an issue where clicking on a rendered element triggers the error message TypeError: matchesSelector is not a function. ...

Transmitting information to the main Vue class component

I'm facing an issue with a Vue component that I've defined using Vue class components. Here is the code snippet: @Component export default class MyComponent extends Vue { value = 0; } My requirement is to create multiple instances of this comp ...

Is there a way to retrieve the JavaScript Console response code using Python and Selenium's execute_script method?

I am running a JavaScript fetch request in the Chrome developer console using Selenium's execute_script() function. The request performs as expected, but I want to set up a function that can verify if the response is a 403 status code. Is there any Se ...

Updating an SQL table with PDO using an array

I'm new to PDO and I'm facing challenges with using arrays in PDO. I am working on a simple web application that uses PDO syntax. Everything is going smoothly, except for updating multiple values with a single submit button. Below is the HTML FO ...

Assigning controller variables within an ajax request

I'm new to AngularJS and I have a question about controller attributes. I've created an attribute called 'anuncio', which contains an array of objects as shown below: var anuncioModule = angular.module('anuncioModule',[]); a ...

The AJAX request encountered an error due to an Unexpected End of JSON Input

My AJAX code is encountering an error message. parsererror (index):75 SyntaxError: Unexpected end of JSON input at parse (<anonymous>) at Nb (jquery.min.js:4) at A (jquery.min.js:4) at XMLHttpRequest.<anonymous> (jquery.min.js: ...

What is the best way to automatically close a parent popup window when the child popup is

Currently, I am developing a web application using Angular that requires managing nested popups. Specifically, in my scenario, I initiate Popup 1 and from within that popup, I trigger another popup (Popup 2) upon clicking "delete." My goal is to ensure tha ...

Utilizing the reduce method to transform an array containing nested arrays into a different structure

I'm having trouble figuring out how to restructure the array below. I attempted to utilize the reduce function in JavaScript but unfortunately, I couldn't make it work. So far, this is the function I have come up with: var comb = [] var setEle ...

I am having trouble with my jQuery login function not properly connecting to the PHP file

Hey there, I've been working on creating a login system from scratch by following an online tutorial. The initial Javascript is functioning properly as it detects errors when the inputs are empty. However, once I enter text into the input fields and c ...

Enhancing search results with data retrieved from a jSON response

At the moment, I am using a logic to generate a list of titles. Now, I would like to include data from the response along with the code for each title in the list. const title = responseData.map(item => { return { label: item.title, val ...

Under what circumstances would you need to manually specify the displayName of a React component?

After coming across an article (linked here: https://medium.com/@stevemao/do-not-use-anonymous-functions-to-construct-react-functional-components-c5408ec8f4c7) discussing the drawbacks of creating React components with arrow functions, particularly regardi ...

What steps can be taken to ensure that JSON.parse() interprets all numbers as BigInt values?

I'm dealing with numbers in JSON that exceed the limits of the Number type, so I'd like to convert them to bigint. How can I do this? {"foo":[[0],[64],[89],[97]],"bar":[[2323866757078990912,144636906343245838,44169598393274215 ...

The value of $parent.$index will consistently be 0 in all cases

I am currently dealing with a nested ng-repeat situation where I am attempting to determine the parent's index. Due to the fact that it is being arranged post-process, the standard ng-repeat="(step_index, step) in flow" method is not working for m ...

Error message "Exceeded the maximum call stack size" encountered during Vue-router authentication

I am currently in the process of developing a dashboard using Vue, Vuex, and Quasar. However, I have encountered an authentication error that is preventing me from progressing. Additionally, I need assistance in ensuring that when a user is already logged ...

Grunt is your go-to resource for instructions on executing these tasks before the main program

Before launching my app, I need to make sure a specific grunt task is executed first: node app.js I'm having trouble finding information on how to automatically run and complete a Grunt task before initiating a node command. In particular, I have T ...

I am interested in showcasing a distinct screen layout specifically designed for mobile device viewing

Looking to display different screens for PC and smartphone users. I am using react, Typescript, and next.js for development. Specifically, I need to show user.tsx when accessing the /user URL from a PC, and Accessdenied.tsx when accessing it from a smartp ...

The number of subscribers grows every time $rootscope.$on is used

I currently have an Angular controller that is quite simple: angular.controller('appCtrl', function ($scope, $rootScope) { $rootscope.$on('channel.message', function () { // do something here } }); In addition, I have a ...

Guide to fetching and returning data from AJAX using a function

In my JavaScript file, I have a function that retrieves a value asynchronously from the server: function retrieveValue(userId) { $.ajax({ type: "POST", url: "http://localhost/bghitn/web/app_dev.php/get_number_of_articles", data ...