Substitute terms with the usage of array map

Here is an array for you

(2) ['beginning=beginner', 'leaves=leave']

as well as a string

its beginner in the sounds leave

that has been converted to an array using the following code

var words = text.split(' ');

My goal is to replace beginner with beginning and leave with leaves. Since there are only two elements for now, I plan to do it within a for loop. Can this be achieved using the map method?

this.words.map((words, i) => console.log(words));

Important: Only the first instance should be replaced.

If you have any solutions, I would greatly appreciate it. Thank you

Answer №1

Is this the correct solution to your query?

const arrayStrings = ["start=starters", "exit=exits", "noise=noises"];

let sentence = "start the noises exit";

arrayStrings.forEach((stringMap) => {
  const stringArray = stringMap.split("=");
  sentence = sentence.replace(stringArray[1], stringArray[0]);
});

console.log("sentence", sentence);
// "start the noises exits"

Answer №2

You can achieve the same result without using a nested loop by making some compromises on space optimization.

One approach is to create a mapping object for replacement values and leverage array methods such as map(), forEach(), join(), along with string methods like split().

const wordPairs = ["beginning=beginner", "leaves=leave", "sound=sounds"];
let sentence = "its beginner in the sounds leave beginner";
const replaceObj = {};
const breaks = wordPairs.forEach(pair => {
  let elements = pair.split("=");
  replaceObj[elements[1]] = elements[0];
});

const result = sentence.split(' ').map((word) => {
  if (word in replaceObj) { 
    let value = replaceObj[word]; 
    delete value; 
    return value; 
  }
  return word;
}).join(' ');

console.log(result);

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

using jquery to retrieve selected values from multiple dropdown lists

I am working with a grid where each row contains a drop-down list to choose a state. When the form is submitted, I want to retrieve the selected value from each row (skipping if none selected). <select name="state" class="dd1"> &l ...

A guide on integrating MongoDB, Mongoose, Express JS, and Node JS for effectively adding prices

Currently adding various documents to the database: await TestMOdel.insertMany([ { Model: "Samsung", price: 45000, OS: "MS DOS", }, { Model: "Wipro", pr ...

Accessing objects using string literals is restricted! I am encountering an issue while attempting to access the route parameter 'id' via a dynamic ID

Let's take a look at my custom [app-routing.modulse.ts] module: const appRoutes: Routes = [ { path: '', redirectTo: '/recipes', pathMatch: 'full' }, { path: 'recipes', component: RecipesComponent, child ...

Reverse row changes in Angular Ag-Grid with the click of a button

Developed using Angular and JavaScript technologies. The AG-Grid consists of editable records with the first column being a checkbox. When changes are made to any selected records, clicking on a particular record's checkbox and then pressing a button ...

What is the reason for the continual influx of new users being added to the database?

I have a Node.JS and MongoDB console application where I've implemented adding users in one file and outputting all collection objects to the console in another file. When running the command - node scripts/get_all_users.js, both existing users are di ...

How can I conceal child <div> elements when the parent div is resized?

Struggling to implement a zoom in/out feature on my web app using the jqueryUI slider. Having trouble handling cases where the parent div shrinks too much, causing issues with the child containers. <div class="puck originator inline-block" style="w ...

populate 3 input fields using the dropdown menu with the help of AJAX

Hello, I am new to PHP and Ajax. I have a select box where users can choose an option, upon which information should automatically fill in four text boxes. Someone recommended using jQuery my initial code. Here is my PHP code: if(isset($_GET['userna ...

Collect the GET parameters as an array of strings when there is only one value

How can I properly pass a string array as a parameter for a GET call? // Passing one value param: filters=Something value: filters: 'Something' // Passing multiple values param: filters=Something&filters=Something else value: filters: [ &ap ...

Angular2 form builder generating dynamic forms based on results of asynchronous calls

When creating my form, I encountered a challenge with passing the results of an asynchronous call to the form builder. This is what I have attempted: export class PerformInspectionPage implements OnInit { checklists: any; inspectionform: FormGroup; n ...

What is the CSS method for altering the color of a slider's runnable track upon selection?

Seeking assistance in changing the slider track color upon selection. Struggling to achieve the desired outcome of altering the color as it slides. CSS: /* Custom Styles */ .text-size-slider { line-height: 100%; font-size: 14px; position: relative ...

Determine if an element is being hovered over using jQuery

How do I determine if the cursor is hovering over an element using jQuery or JS? I attempted to use $('#id').is(':hover'), but it doesn't seem to be functioning as expected. It's worth mentioning that I am calling this line ...

One common issue is being unable to target input[type=file] when multiple forms are present on a page using JavaScript

Question: I have multiple dynamic forms on a web page, each with a file input field. How can I specifically target the correct file input using $(this) in JavaScript? Here is an example of one of my forms: <form enctype="multipart/form-data" action="c ...

Combining functions does not result in a callable function, even when the parameters fulfill the constraints of each individual function

I have encountered an issue while trying to compile a Typescript snippet: function foo(v: string) { return 'foo'; } function bar(v: string | number) { return 'bar'; } const notCallable: typeof foo | typeof bar = function() {} as any; ...

The alarm feature is malfunctioning

I have been struggling with a simple alarm application that I created using jQuery and Javascript. The issue lies in the alarm functionality not working as expected. Below is the relevant code snippet: var today = new Date(); var h = today.getHours(); var ...

Conditions are in an angular type provider with AOT

I am facing an issue with my Angular project that is compiled using AOT. I am trying to dynamically register a ClassProvider based on certain configurations. The simplified code snippet I am currently using is below: const isMock = Math.random() > 0.5; ...

How can JavaScript be used to prevent pinch and zoom functionality on Google Maps?

In my project, I am utilizing Google Maps but I want to disable the zooming effect on the map. To achieve this, I have disabled the zoom control using zoomControl: false,. However, this modification only applies to desktops and laptops as they do not suppo ...

Triggering a JQuery Toggle Button

This is the code I'm currently working with: $('.access a').toggle(function() { $('link').attr('href', 'styles/accessstyles.css'); $('body').css('font-size', '16px'); }, fu ...

Using Angular 2: Applying a specific class to a single element with [ngClass]

I have a header table with arrows indicating sorting order, using Bootstrap icons. However, when I click on a column, all columns receive the icon class. Here is an example of what I mean: https://i.sstatic.net/CAS81.png Below is the code snippet: HTML ...

Display website when clicked

When creating a website similar to , one issue that I am facing is the ability to scroll down before clicking the "proceed as anticipated" button. This feature seems to defeat the purpose of having the button trigger an automated scrolling effect if users ...

Utilizing TypeScript's conditional return type with an object as a parameter, and incorporating default values

Is it possible to create a function where the return type is determined by a string, with some additional complexities involved? I'm looking to achieve the following: The parameter is contained within an object The parameter is optional The object it ...