Change specific instances of a string based on the chosen index in JavaScript

Looking for a solution to fix a bug in my self-made autocomplete feature. Consider this scenario where I need to autocomplete the final word in an incomplete sentence:

let text = 'Hello there, I am her'

My current method involves the user pressing ctrl + enter to autocomplete with a suggested word displayed on the page. Let's assume the suggestion here is 'here'. Additionally, my controller tracks the insertion cursor position (index).

If I use the replace function like so:

text.replace(word, suggestion);

(In this case, 'word' is 'her' and 'suggestion' is 'here'), it will replace the first occurrence of 'her'. The challenge lies in replacing a specific index within the text string as there can be multiple instances of the word throughout. Is there a more efficient way to achieve this rather than using cumbersome if conditions?

(For context, I am implementing this functionality with Angular keydown/keyup events)

EDIT>>>>> This query differs from the linked question since the problem at hand involves supporting users who may revisit previous sections of their sentence to autocomplete a new word.

Answer №1

Let's say you have a specific position within a string and need to replace a certain number of characters (representing an incomplete word). Would the following code be effective in achieving this task?

let words = 'appl and appl and appl'

function swapLetters(str, position, length, replacement) {
    return str.slice(0, position) + replacement + str.slice(position + length);
}

console.log(swapLetters(words, 0, 4, 'apple'))
console.log(swapLetters(words, 9, 4, 'apple'))

Answer №2

Starting you off with a helpful direction.

const phrase = 'Hey let\'s swap all instances of hey with Hi';
const parts = phrase.split(' ');
for (let j = 0; j < parts.length; j++){
 if(parts[j].toLowerCase() === 'hey')
   parts[j] = 'Hi'
}
const newPhrase = parts.join(' ');
console.log(newPhrase); //"Hi let's swap all instances of Hi with Hi"

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

The innerHTML function is providing plain text instead of HTML content

I am currently working on an application in AngularJS and I have a function that removes #(hashes) and turns them into links. $scope.getAllHashes = function(event){ var x = event; var collect = ''; var link = ''; for ...

Having trouble accessing the $scope variable in Ionic 1/Angular

Looking at this block of HTML: <div class="item item-icon-left" ion-datetime-picker="" time="" ng-model="timeValue"> <i class="icon ion-ios-clock positive"></i> <p><strong">{{timeValue | date:'HH:mm ...

Local variable reference getting lost in a loop during a jQuery Ajax call

Currently, I am facing an issue with my jQuery ajax calls within a loop. The problem arises when each ajax call returns and I need to retrieve a specific value associated with the original call. However, due to further iterations in the loop, the value of ...

Combining selected options from an AngularJS dropdown menu

I'm currently facing an issue while attempting to sum up my $scope values. Here is the code I'm using: $scope.total = ($scope.list_category1.id || 0) + ($scope.list_category2.id || 0) + ($scope.list_category3.id || 0); Unfortunately, I can&apo ...

Encountering a Restangular error: "The 'then' function is not recognized" while attempting to resolve a promise

Welcome to my service. (function() { 'use strict'; angular .module('amazonScraperWebClient') .factory('dataService', dataService); /** @ngInject */ function dataService(Restangular) { Restangular.setBas ...

Error message: "Uncaught TypeError in NextJS caused by issues with UseStates and Array

For quite some time now, I've been facing an issue while attempting to map an array in my NextJS project. The particular error that keeps popping up is: ⨯ src\app\delivery\cart\page.tsx (30:9) @ map ⨯ TypeError: Cannot read pr ...

Verify if items in a list contain a source from a variable and then execute code - jQuery / JavaScript

My goal is to compare the variable SRC to the image sources in a list from my HTML. If it matches, I want to execute a specific function. Unfortunately, it appears that this process is not functioning correctly. For a live example, please visit the follow ...

Refreshing web pages using AJAX

I currently have an application that includes a search feature where users can look up items in the database. The search functionality is working well with AJAX, but I'm now looking to incorporate this AJAX functionality into my pagination system. Spe ...

How to convert an array of keys and an array of values into an array of objects using JavaScript

My question is similar to the one found here: Merging keys array and values array into an object using JavaScript However, I am unable to find a solution for my specific scenario. If I have these two arrays: const keys = ['x', 'y', &ap ...

The error message "Node.js is throwing a next() error that is not a

var express = require('express'); var app = express(); var middleware = { requireAuthentication: function(req, res, next){ console.log("private route hit"); next(); } }; app.use(middleware.requireAuthentication()); app ...

Incapable of composing text using the MUI SearchBar

I'm having trouble with my Material UI search bar - it's not letting me type anything into it. How can I resolve this issue? Despite trying the suggested code snippets from other answers, I keep encountering errors when integrating them into my ...

Setting the default tab in easyTabs to be all-powerful

My ajax content is being loaded into a div-container through various navigation links, and I am using the script below to establish the defaultTab: $(document).ready( function() { $("#tab-container").easytabs({updateHash: true, defaultTab: "li:eq(3)"}); ...

Utilize Next.js with Axios for making an HTTP request to a Laravel Lumen endpoint, then showcase the retrieved data within the Next.js

I currently have a Next.js application that utilizes Axios to make calls to Lumen endpoints. The Axios HTTP client functions are organized in a separate folder named services/index.tsx, with sample code as follows: export const register = async (payload: a ...

Ways to display the modal once the user initiates the action

Is there a way to delay loading my modal HTML codes until after the user clicks a button, rather than having them load automatically with the template? HTML <!-- Template Codes--> <button data-toggle="modal" data-target="#modal-content" type="bu ...

Reasons Why Vue Component Does Not Update When Select Changes

I'm encountering an issue with a form that is supposed to change text within a vue component based on the selection made in a select box. To demonstrate the problem I'm facing, I've created a simplified version of the code on jsfiddle: http ...

Preflight request rejection due to access control check failure in React and Express

I am facing a similar issue to this question, but my problem is specific to using Express with React on the frontend. The error I am encountering is: https://i.sstatic.net/1OIfy.png Access to fetch at 'http://localhost:8000/api/users/auth/github& ...

Using Firebase Realtime Database, this React dropdown menu is populated with options in real-time. Combining the features

I'm currently facing an issue with a dropdown that is supposed to loop through data fetched from the Firebase realtime database. The goal is to assign a selected value to a Formik form for saving it to another object in the database. In my database, ...

The x-axis in c3.js is experiencing issues with plotting when there is interval data in DST time

Trying to create a graph using the c3.js library with an x-axis interval of time. The intervals are determined by selecting a date range in the date picker. For example, if we select the dates 2016-03-13 00:00 to 2016-03-13 04:00, we add 15 minutes to ...

Enhance your coding experience with Firebase Autocomplete on VScode

Recently, I installed VScode along with the necessary packages for JavaScript development. As I started writing code involving Firebase, I noticed that the autocomplete feature, which worked perfectly fine in Xcode, was not functioning in VScode. How can I ...

Breaking up ui-router state definitions into separate modules

In my endeavor to structure an Angular application based on features/modules rather than types, I have encountered difficulties in modularizing state definitions for ui-route. I have segmented my app into modules app.core, app.company, app.products. Inste ...