Swapping one word with a different word in a sentence without altering any other word that shares a common substring in Javascript

Is there a way to replace the word "has" with "had" in a string without affecting instances of the word "hash" that contains the substring "has"? I'm currently using the function below but it also replaces "has" within "hash". Any suggestions on how to address this issue?

function replace() {
    sentence = sentence.replaceAll("has", "had");
}

Answer №1

Enclose the word to be substituted with word boundaries:

let sentence = "A girl who has a cat loves to play";
let newSentence = sentence.replace(/\bhas\b/g, "had");
console.log(newSentence);

It's important to note that I utilized the regular replace function with the global flag /g, which produces the same outcome as using replaceAll.

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

By utilizing the HTML element ID to retrieve the input value, it is possible that the object in Typescript may be null

When coding a login feature with next.js, I encountered an issue: import type { NextPage } from 'next' import Head from 'next/head' import styles from '../styles/Home.module.css' import Router from 'nex ...

Encountering problems when attempting to effectively filter a list of products using data

<div id="prod"> <div class="content" data-brand="Andrew" data-price="1000" data-store="JCPenny">Andrew</div><br /> <div class="content" data-brand="Hill" d ...

Clicking in Javascript can hide the scroll and smoothly take you to the top of the page

For my website, I found this useful tool: It's been working great for me, but one issue I've encountered is that when I click on a picture using the tool, its opacity changes to 0 but the link remains in the same spot. I'm trying to figure ...

Creating a custom Shape Geometry that is derived from BoxBufferGeometry

Looking to create a ShapeGeometry that can be defined by a list of points representing the shape boundary or faces, along with a corresponding list of textures for each face. While the BoxBufferGeometry class provides a starting point, I am in need of guid ...

The datepicker UI triggers the onChangeMonthYear event before executing the beforeShowDay function

I am currently using the jQuery Datepicker UI (http://jqueryui.com/datepicker/) My goal is to dynamically color specific days based on data retrieved from an AJAX call. This is the current setup: $(document).ready(function() { getAllDays(); $("# ...

"Error encountered when attempting to read a file from a dialog box using Electron due to

I am currently working on an electron program that requires reading a file in order to apply another program onto it. At this stage, my main goal is to successfully read and log the content of the file. Below is the code snippet I have implemented in a sc ...

Change the defaultValue of a React component following a successful request

In my project, I am dealing with a DropDown component from a separate library that renders various options. The component supports an array of objects as its source and setting a default value is straightforward when the list is static. However, I'm f ...

Insert a fresh item into a MongoDB document array exclusively when a specific requirement is fulfilled

I am working with a mongoDB document structure that looks like this: Game = { _id: 'randomObjectId', players: [Array of players ObjectIds], maxPlayers: 2, status: 'created' (or 'fully-booked') } My goal is to update t ...

Building on the Vuejs3 and Vuex4 framework, create a conditional rendering feature that triggers upon

I have a unique setup where custom objects are used to hold child objects full of data. The child objects start with null values for all properties, allowing them to be filled with data from remote sources when referenced. This results in a lazy-loading sy ...

Tips to successfully save and retrieve a state from storage

I've encountered a challenge while working on my Angular 14 and Ionic 6 app. I want to implement a "Welcome" screen that only appears the first time a user opens the app, and never again after that. I'm struggling to figure out how to save the s ...

How can I apply an underline effect when hovering over navigation links in a responsive menu?

I've successfully added an underline effect on hover for the navigation menu. However, I encountered an issue with the responsiveness of the menu. When viewed on screens smaller than 600px, the underline effect covers the entire width of the block ins ...

What are some ways I can customize this jQuery :submit selector demonstration?

After reviewing the jQuery example provided here, I am curious about how to adjust the code in order to change the color of a cell only when the value of the submit button within that cell meets certain criteria. For instance: var submitEl = $( ...

AngularJS can be used to display a webpage

After facing the need to print a given page using AngularJS, I came up with a simple solution as shown below: <div class="modal fade" id="extrait" aria-hidden="true" data-backdrop="false"> <table class="table table-hover table-bordered" i ...

Which Express.js template allows direct usage of raw HTML code?

I am in search of a template that utilizes pure HTML without any alterations to the language, similar to Jade but keeping the HTML as is. The reason behind this inquiry is: I prefer the simplicity and clarity of HTML I would like to be able to easily vi ...

The jQuery mobile tap event triggers the vclick event

I have been developing a jQuery mobile application that needs to be functional on both mobile devices and PCs. To detect finger events, I am utilizing the jQuery Finger plugin (): $('body').on('tap', 'image', function(e) { ...

import component dynamically from object in Next.js

Currently, I have a collection of components that I am aiming to dynamically import using next/dynamic. I'm curious if this is achievable. Here's the object in interest: // IconComponents.tsx import { Tick, Star } from 'components ...

Exploring nested arrays in JSON through iteration

Here is the JavaScript code I am working on (the "data" variable is retrieved from a json call): if (data.projectReports.length) { for (var i in data.projectReports){ var report = data.projectReports[i]; $('#reports').append( & ...

Using regular expressions in JavaScript to substitute an equal sign that is immediately followed by a line break

I need help creating a regex expression that will remove equal signs followed by a new line. For instance, the text below shows each line ending with an equals sign and a new line character. <p style=3D"border-bottom: 1px solid lightgrey; padding- ...

Ways to verify if all javascript and css files have been successfully loaded

I have been exploring different ways to notify users if certain resources do not load correctly. So far, I have come across the following methods: For CSS, I stumbled upon an example in the source code of Trello: <div id="nocss"> Your browser ...

Retrieve the initial index from a sorted array in JavaScript using an array

'I am looking to organize an array in numerical order, but I also need to be able to track the original index of each element after sorting. Consider the initial array: ptsGP = [3,8,2,5,6,9,8,4] Below is the code I am currently using to sort the ar ...