Replace a string in an array using JavaScript

I may be overlooking something very obvious, but here is my dilemma. I am trying to convert [ 'hr' ] into [ '* * *' ]. This is what I tried:

var hr = jsonml[i]

console.log(hr)
// outputs: [ 'hr' ]
hr.replace(/hr/g, '* * *')

However, I am encountering this error:

TypeError: Object hr has no method 'replace'

Can someone point out what I am missing here?

Answer №1

Since the variable hr is of type Array, you can attempt the following:

hr[0] = hr[0].replace(/hr/g, '* * *');

Alternatively, you can try:

hr = hr[0].replace(/hr/g, '* * *');

Answer №2

The variable called hr is actually an array that holds a single string element. Here is how I would handle it:

if (hr.length > 0)
    hr[0] = hr[0].replace(/hr/g, '* * *');

Alternatively, you could use a loop to handle multiple elements:

for (var i = 0; i < hr.length; i++)
    hr[i] = hr[i].replace(/hr/g, '* * *');

This is useful in case the hr array contains more than one element.

Answer №3

Check the type of the specific object :

alert(typeof hr);

Upon running this code snippet, you'll realize that the object is actually an array!

Now, implement the following code:

for (let j = 0; j < hr.length; j++) {
  let output = hr[j].replace(/hr/g, '* * *');
}

Answer №4

Here is a concise solution that fulfills the exact requirements posed by the original poster:

hr = [hr[0].replace('hr', '* * *')];

There is no necessity for utilizing a regular expression for the replacement in this context.

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

Every time I attempt to execute mupx deploy, an error message appears

issue in console shubhabrata@shubhabrata-VirtualBox:~/Meteor/myapp$ mupx deploy Meteor Up: Advancing Meteor Deployments for Production Configuration file : mup.json Settings file : settings.json “ Discover Kadira! A powerful tool to monitor yo ...

What is the most effective way to incorporate the DOMContentloaded event listener into the document using nextJS?

I am working on integrating an HTML code snippet into my Next.js project. The snippet includes an external script with a createButton function. <div id="examplebtn"></div> <script type="text/javascript"> //<![ ...

Can someone please help me figure out how to detect active users within my Next.js application while utilizing Supabase authentication?

I'm looking for a way to recognize users on my app in order to display green badges as visual cues. After logging into my app using Google OAuth, the session remains active even though I logged out days ago. I am unsure of the most effective algorith ...

When displaying a collection of components, clicking a button will always select the most recent element in the array

Can you explain why this code won't work in a React environment? Every time the button is clicked, it picks up the value "name" from the last element in the array. In this example, the dialog will always display the name "John2". import React from "r ...

What is the best way to refresh the slick jQuery plugin for sliders and carousels?

I am currently facing an issue with two buttons that have the same function. The purpose of these buttons is to retrieve data from an API, convert it to HTML, and then append it to a <div> using jQuery. Finally, the data is displayed using the slick ...

Display the personalized list of user items on the MERN dashboard

I'm currently developing a React booking platform that interacts with my backend through a Rest API using axios and redux. My challenge now is to display personalized reservations and rooms for each user on the website. However, I'm facing an iss ...

When working with Firebase, I am required to extract data from two different tables simultaneously

When working with Firebase, I have the need to extract data from tables/nodes. Specifically, I am dealing with two tables - one called jobs and the other called organisations. The outcome I am looking for: I want to retrieve all companies that do not hav ...

Updating a nested property within an array of objects in MongoDB

Storing grades for an online education application using MongoDB. Here is a sample classRoom document stored in my mongoDB database. StudentGradeObjs are kept in an array within a GradeObject. GradeObjs are stored in an array of GradeObjects inside a class ...

Express: adding a question mark to the URL when submitting the form

Upon submitting a form with a "?" in the URL, I noticed that when posting it redirects me to the page and still returns a "?" in the URL. Directory: server.js, index.html, package.json, package-lock, src/models/form.js server.js: const express = require( ...

obtaining data from a JSON object in Node.js

Retrieve response in function node.js [ { instrument_token: '12598786', exchange_token: '49214', tradingsymbol: 'AARTIIND21JAN1000CE', name: 'AARTIIND' }, { instrument_token: '125998 ...

Tips on personalizing the vue-filemanager interface within Laravel

I'm currently utilizing the Laravel file manager package from here, which provides a pre-compiled JS file or allows for direct use of the vue-component through npm from here. Unfortunately, in both options, the front-end is not customizable. I have i ...

Updating an HTML element by using the input value in a text field with JavaScript/jQuery

Although it may seem straightforward, I am new to Javascript and struggling to find or create the script I need. I have a list of BIN numbers for credit cards and want to extract the first 6 digits of the card number field to determine the type of card, an ...

Issue: TypeError - 'process.env' can only accept a configurable while installing windows-build-tools

Unable to successfully download installers. Encountered an error: TypeError: 'process.env' can only accept a configurable, writable, and enumerable data descriptor. I attempted to resolve this issue by running the command npm install --global wi ...

Discover the largest possible value

With two arrays and a truck at my disposal, I'm tasked with determining how many units can fit in the truck. The arrays are as follows: boxes = [3, 1, 6] units_per_box = [2, 7, 4] truck_size = 6 Each box is of uniform size and the truck can accommoda ...

Failure when running npm start command in Nest js

After setting up a fresh Nest js on a new EC2 machine, I encountered an error when trying to run it for the first time. The error message indicated that the npm install process failed abruptly without any visible error: ubuntu@ip-172-31-15-190:~/projects/m ...

Retrieve JSON information using AJAX

As I am new to JSON and Ajax, the question I have may seem basic. When I try to display data from my JSON object containing 'name', 'task', 'date', and 'status' using Ajax, it does not show up on my page. Below is m ...

Error: The function $(...).live is not defined within the MVC framework

I included a dialog box using jQuery in my MVC form. Here is the code snippet from my View : <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></scr ...

Using a JavaScript loop to modify the color of the final character in a word

I am curious to find out how I can dynamically change the color of the last character of each word within a <p> tag using a Javascript loop. For example, I would like to alter the color of the "n" in "John", the "s" in "Jacques", the "r" in "Peter" ...

Preventing HTML form submission after displaying an alert in Vanilla JavaScript

I have created a quiz using HTML with validation. The next step is to score the quiz in JavaScript. The scoring system works fine, but I want to prevent the form from posting to result.html if the user scores 0 on the quiz. I've managed to display an ...

Struggling to extract text from within a <p> tag on an Ionic 1 app page on iOS

After developing an ionic-1 application for iOS and Android devices, I encountered an issue with displaying mobile numbers in one of the views. The numbers are contained within <p> tags. While users can click and hold on a number to copy it on Andr ...