Swap out any terms in a sentence that correspond to words found in a different array

Looking to prefix words in a string that match specific 'filter' words with a # symbol.

Here's what I've tried:
let wordsArray = ['she', 'smile'];
let sentence = 'She has a big smile';
let sentenceArray = sentence.split(" ");
wordsArray.forEach((word, index) => {
    sentenceArray.forEach((sWord, sIndex) => {
        if (sWord === word) {
            sentenceArray[sIndex] = `#${sWord}`;
            console.log(sentenceArray);
        }
    });
});

Here's the output in the console.

app.js:17 (5) ["She", "has", "a", "big", "smile", She: "#She"]
 app.js:17 (5) ["She", "has", "a", "big", "smile", She: "#She", has:
 "#has"] app.js:23 She has a big smile

Any suggestions on where the issue might be?

Answer №1

Repl Demo

If you want to modify specific words in a sentence, you can utilize the Array.map method. This allows you to iterate through each word, checking if it matches any predefined words in an array, and then replacing it with a "#" symbol if a match is found.

const wordList = ['happy', 'excited'];
const sentence = 'She is happy and excited';
const sentenceArray = sentence.split(" ");
const modifiedSentence = sentenceArray.map((word) => {
  const matchIndex = wordList.indexOf(word.toLowerCase());
  return (matchIndex !== -1)
    ? '#'.concat(word)
    : word;
});

Answer №2

The index should be used as the second parameter in the forEach callback, indicating the current iteration position, rather than the value. Remember to apply toLowerCase to the words for comparison with the lower-cased versions in the wordsArray:

let wordsArray = ['she', 'smile'];
let sentence = 'She has a big smile';
let sentenceArray = sentence.split(" ");
wordsArray.forEach((vals) => {
    sentenceArray.forEach((sVal, j) => {
        if (sVal.toLowerCase() === vals) {
            sentenceArray[j] = `#${sVal}`;
        }
    })
});
console.log(sentenceArray)

Instead of using a nested loop, consider creating a Set from the wordsArray for better efficiency (O(n) instead of O(n ^ 2)), as well as for a more elegant solution:

const wordsArray = ['she', 'smile'];
const wordsSet = new Set(wordsArray);
const sentence = 'She has a big smile';
const result = sentence.split(" ")
  .map(word => wordsSet.has(word.toLowerCase()) ? '#' + word : word);
console.log(result);

Answer №3

wordsArray.forEach((word) =>sentence = sentence.replace(new RegExp(word,"ig"),"#"+word))

This function loops through each word in the filter and replaces those words in the sentence using a regular expression with the pattern new RegExp(word, "ig"). The first argument represents the word to be found and the second argument "ig" includes flags: "i" for ignoring case sensitivity and "g" for a global search.

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

Incorporate dynamic animations into text wrapping using React

Currently, I am in the process of learning React and have successfully created a flexbox with 6 child containers using the wrap property. Now, I am looking to add animation when the containers wrap onto a new line. I attempted to add a transition animatio ...

Can someone explain the variance between these two script codes? Are they entirely distinct, or can I utilize just one source?

<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> It appears that one script is for jQuery and the ...

Exploring navigation options in VueJS with the router

I recently completed a tutorial on integrating Okta OAuth with VueJS. In my application, I have set up a default page that displays the "App.vue" component and switches to the "About.vue" component upon clicking the "/about" route. However, I encountered a ...

The debounced function in a React component not triggering as expected

I am facing an issue with the following React component. Even though the raiseCriteriaChange method is being called, it seems that the line this.props.onCriteriaChange(this.state.criteria) is never reached. Do you have any insights into why this.props.onC ...

Here is a guide on updating HTML table values in Node.js using Socket.IO

I successfully set up socket io communication between my Node.js backend and HTML frontend. After starting the Node.js server, I use the following code to emit the data 'dRealValue' to the client side: socket.emit ('last0', dRealValue) ...

Building a 'Export to CSV' button using a PHP array within the Wordpress Admin interface

I have successfully populated a PHP multi-dimensional array using a custom function and now I want to enable my admin users to download the data. After researching, I came across a PHP function that can export an array to CSV file. I integrated this funct ...

Emphasize the element if it is present in both arrays

I am new to working with MySQL and I'm interested in creating a table that resembles a grid of rows and columns labeled from A1 to C22 (which I'll refer to as wells). The output of my MySQL script should look like the following arrangement (I wis ...

The compatibility issue between Angular JS App and JSPDF is causing malfunctions specifically in Internet Explorer

I am currently working on an Angular JS application that utilizes JSPDF for generating PDFs. While the PDF generation functionality works perfectly fine on Chrome, Firefox, and Safari, it encounters issues on Internet Explorer (IE). The specific error mes ...

Error Occurred while Uploading Images using Ajax HTML Editor with JSON Data

I am facing an issue with my AJAX HtmlEditorExtender, specifically when trying to upload an image. The error message I receive is as follows: JavaScript runtime error: Sys.ArgumentException: Cannot de-serialize. The data does not correspond to valid JSON. ...

What is the proper way to designate a manifest.json link tag on a limited-access website controlled by Apache shibboleth?

The issue arises when attempting to access the manifest.json file. It has been declared as follows: <link href="manifest.json" rel="manifest"/> Is it possible to declare the manifest tag inline, or what would be the most effective way to declare it ...

Tips for controlling numerous tabSlideOUt tabs on a single webpage

Is there a way to implement multiple tabSlideOut functionalities on a single page, similar to the examples provided in the following links: source code on GitHub and Fiddle Example? Specifically, I am looking to have tabs that can be toggled, ensuring tha ...

Converting hierarchical JSON data into a table with rowspan using Angular

I am facing a challenge in creating a table using nested JSON obtained from an API. I am unsure how to dynamically merge cells when needed, especially since the JSON structure can be nested up to 6 or 7 levels. Desired Table : Expected Table Current Ou ...

display the $scope as undefined in an angular application

Below is my code snippet: var exchange = angular.module('app', []); exchange.controller('ExchangeController', ExchangeController); function ExchangeController($scope, $http) { $scope.items = []; $http ...

Learn how to default export React with withRouter, all while taking advantage of Material UI's makeStyles

I have been working on integrating Material UI makeStyles with class components, passing useStyles as props while default exporting it in an arrow function. export default () => { const classes = useStyles(); return ( <LoginClass classes={cl ...

Cannot get the before-leave transition JavaScript hook to function properly in Vue.js

I am facing an issue with my variable, transitionName, in the beforeLeaveHook function. Despite attempting to change it to 'left', the value remains stuck at 'right'. Any assistance on resolving this matter would be greatly appreciated. ...

Tips on assigning a value to a cell within a List<int[][]>

I have a situation where I am working with a list called List<int[][]> orgnisms = new ArrayList<>();. This list contains several empty tables with only 0 values, and I am looking to update the value of specific cells. For instance, I need to as ...

Conceal the countdown clock and reveal the message box

I am attempting to create a functionality where the text box will replace the timer when it reaches 0, and then the timer will be hidden. I am seeking a straightforward solution using either the 'v-show' or 'destroy' property in vue.js ...

storing the output from a MySQL array into a PHP variable

My goal is to send SMS to all the members listed in a MySQL table using an API. Currently, I am only able to send the SMS to the first row in the table. However, my intention is to send the message to all records in the table. The code snippet I am using ...

Encountering Internal Server Error when C# WebMethod communicates with JavaScript AJAX call

I've encountered an issue where my AJAX call to a C# WebMethod is not returning the expected result. Instead, it keeps showing an "Internal Server Error" message. A button triggers a JavaScript function: <button id="btn" onclick="Create();">fo ...

Versatile accordion with separate functionalities for items and panels

When I have different functions for clicking on item and title, clicking on the item works fine but clicking on the panel triggers both functions. Is there a way to resolve this so that I can click on the item using Function_1 and click on the panel using ...