Unable to add specific characters to an array

I'm new to JavaScript and ran into an issue with the code below, trying to find the string "Craig" and add it to a new array called "Hits".

var text = "Hey, how are you \ doing? My name is Emily.\ My other friends       name is Craig. My friend Craig is learning JavaScript";
var myName = "Craig"
var hits = [];

for(var i = 0; i < text.length; i++){
if(text[i]=== "C"){
    for(var j = i; j < myName.length; j++ ){
       hits.push(j); 
    }
}
}

Answer №1

The condition in your loop using the for statement is incorrect. Please replace it with the following: j < i + myName.length

for(var j = i; j < i+myName.length; j++ )

Note: There is a more efficient way to achieve this using the indexOf() method.

Answer №2

let message = "Greetings! How have you been lately? I'm known as Samantha. My buddy, Tom, is currently studying Python.";

    let myName = "Tom";
    let matches = [];

    if (message.indexOf("Tom") > -1)
    {
       matches.push(myName);
    }

Here, the indexOf method will indicate the position of the matched string;if the string is not found, indexOf will return -1

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

Get the characteristics of the raphael pie chart

How can I access the attributes of a Raphael pie chart? I'm interested in getting attributes such as stroke color, values (excluding legend), radius, and x/y position. Here's how my pie chart is defined: pie = r.piechart(120, 140, 50, [55, 22] ...

Using JQuery to create interactive dropdown menus with dynamic options

I am exploring the possibility of dynamically updating the choices available in an HTML dropdown menu based on the selection made by a user - consider this sample JSON data: series: [ {name: 'Company X', product: 'X1'}, {name: 'Co ...

Unable to display data retrieved from JSON file

I am encountering an unusual issue while trying to retrieve elements from JSON in JavaScript. I fetch a JSON string from a URL using the following code: // Create Request HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"www.someurl ...

Javascript retrieve the style of an element in every possible state

I am interested in retrieving the line height of an element; it's a simple task. Here is a method that I know works: console.log(document.getElementById("myDiv").style.lineHeight); console.log($("#myDiv").css('lineHeight')) ...

Filtering DataGrid columns with an external button in Material-UI: A step-by-step guide

Imagine having a datagrid table structured as shown below: import * as React from 'react'; import { DataGrid, GridToolbar } from '@mui/x-data-grid'; import { useDemoData } from '@mui/x-data-grid-generator'; const VISIBLE_FIEL ...

Angular - No redirection occurs with a 303 response

Having an issue with redirection after receiving a 303 response from a backend API endpoint, which includes a Location URL to any subpage on my site. Upon attempting the redirect, an error is triggered: Error: SyntaxError: Unexpected token '<&ap ...

Error SCRIPT5009: The term 'fetch' is not defined

Having some issues with my requests using Fetch API! The submit form isn't working in Internet Explorer, showing "SCRIPT5009: 'fetch' is undefined" error! This is an example of how it looks: fetch("url", { method: "P ...

Subclass declaration with an assignment - React.Component

I recently started going through a React tutorial on Egghead and came across an interesting class declaration in one of the lessons: class StopWatch extends React.Component { state = {lapse: 0, running: false} render() { const ...

Identifying memory leaks in Javascript

I've developed a basic script to retrieve the size of a list in redis and display memory usage. It appears that the amount of "heap used" memory is gradually increasing. Could this indicate a memory leak, and what modifications can be made to preven ...

Retrieving information within a loop through the utilization of a left join操作。

Presently, I am utilizing a while loop to fetch user comments from a MySQL table and applying a conditional class to the buttons within the comment div. Each comment contains two buttons: thumbsup button thumbsdown button I aim to assign the class name ...

Can you explain the distinction between angular-highcharts and highcharts-angular?

Our team has been utilizing both angular-highcharts and highcharts-angular in various projects. It appears that one functions as a directive while the other serves as a wrapper. I'm seeking clarification on the distinctions between the two and recomme ...

Next.js encountered an issue: The main export is not a React Component on the specified page: "/"

I keep encountering a persistent error in my Next.js application: Internal error: Error: The default export is not a React Component in page: "/" Despite trying various solutions, the issue persists. Here are the key details of my setup: Next.j ...

Best practices for loading and invoking Javascript in WordPress child themes

After spending countless hours searching for a detailed tutorial on how to properly incorporate Javascript into a WordPress website, I came up empty-handed. Running the Genesis Framework with a child theme on my localhost, I am eager to add a fullscreen b ...

What is the process for configuring environmental variables within my client-side code?

Is there a reliable method to set a different key based on whether we are in development or production environments when working with client-side programs that lack an inherent runtime environment? Appreciate any suggestions! ...

External JavaScript is not functioning

I am encountering an issue with an external JavaScript file not working in my HTML document. Strangely, Firebug is not reporting any failures. However, when I directly run the JS code in my HTML file, it works perfectly. Here is the content of action.js: ...

Text words wrapped in a new line

Below is the code I've been utilizing to wrap lengthy text inputted by users in a textarea for leaving comments: function addNewlines(comments) { var result = ''; while ($.trim(comments).length > 0) { result += comments.substrin ...

``Is there a way to redirect users when they click outside the modal-content in Bootstrap

I have a modal on my website that currently redirects to the homepage when the close button is clicked. However, I also want it to redirect to the homepage when clicking outside of the bootstrap modal, specifically targeting the ".modal-content" class. I ...

How can you efficiently identify and resolve coding errors or typos in your code?

While practicing node.js and express.js, I encountered an issue with finding typos. One such instance was when I mistakenly typed: const decoded = jwt.veryfy(token, config.get('jwtSecret')); instead of jwt.verify. Even though I eventually disc ...

When the "x" close icon is clicked, the arrow should toggle back to 0 degrees

I've been tackling the challenge of creating an accordion and I'm almost there. However, I'm facing an issue where the arrow doesn't return to its original position after clicking the close "x" icon. The toggle works fine but the arrow ...

Occasionally I encounter the message: "Error: Server unexpectedly terminated with status 1."

I created an automated test to check the login page, with testing data stored in a JSON file. Here is the code in index.js: const fs = require("fs"); fs.writeFileSync("testReport.json", "{}", "utf-8"); const { login } = require("./tests/login"); const au ...