Finding and comparing a specific portion of a text in JavaScript: A guide

Can you help me with a JavaScript algorithm that can find a substring within a string?

subStringFinder('abbcdabbbbbck', 'ab')

This should return index 0.

Similarly,

subStringFinder('abbcdabbbbbck', 'bck')
should return index 10.

Would you be able to provide guidance on writing this code?

--UPDATE:

With the help of @Jonathan.Brink, I was able to write code that successfully achieved this:

function subStringFinder(str, subString) {
  return str.indexOf(subString);
}

subStringFinder('abbcdabbbbbck', 'bck') // -> 10

Answer №1

If you're searching for the indexOf function, look no further. This handy function is readily available for use with the built-in string type, as well as with arrays.

For example:

var str = "abbcdabbbbbck";
var n = str.indexOf("bck");
// n is 9

Instead of creating a custom subStringFinder function, consider using the built-in indexOf for a more efficient solution.

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

Is it possible to retrieve all data from the Google translation API?

In my React app, the main component contains this function: componentDidMount(){ const land = ["Afrikaans", "Albanian", "Amharic", "Arabic", "Armenian", "Assamese", "Aymara", &qu ...

What is the best way to create an express route for a delayed string response that is loaded only after an API call promise is fulfilled?

app.get(`/${sumName}`, async (req, res) => { const link = `https://na1.api.riotgames.com/lol/league/v4/challengerleagues/by-queue/RANKED_SOLO_5x5?api_key=${RiotKey}` const response = await fetch(link); let data = await response.j ...

Utilize Jasmine's AJAX spy to intercept and inspect the error request

I am encountering an issue while trying to monitor the ajax error request and receiving the following error message. Can someone assist me with this? TypeError: e.error is not a function Code snippet for JS testing : function postSettings() { $ ...

The absence of data in a c# web api controller is causing issues with jQuery AJAX post requests

When I am sending data to a c# web api controller, I use the following method: $.ajax({ type: "POST", url: "menuApi/menu/Cost", data: JSON.stringify(order), contentType: "application/json", success: function (data) { window.alert(&apo ...

What is the best way to establish and concentrate on a fresh component in AngularJS?

I am working on a form that has a dynamic number of inputs, which is controlled by AngularJS. <body ng-app="mainApp" ng-controller="CreatePollController" ng-init="init(3)"> <form id="createPollForm"> <input class="create-input" ...

Cleanse the email using express-validator, but only if it is recognized as an email format; otherwise, disregard

Currently, I am developing an API that requires users to input their username and password for authentication purposes (login functionality). Users have the option to enter their email, username, or mobile number. To ensure consistency, I need to normalize ...

Pause for a moment before commencing a fresh loop in the FOR loop in JavaScript

Behold, I present to you what I have: CODE In a moment of curiosity, I embarked on creating a script that rearranges numbers in an array in every conceivable way. The initial method I am working with is the "Selection mode", where the lowest value in th ...

bing translator API: the variable text is translated with no content

I'm encountering an issue while working with javascript and PHP. The PHP code seems to run fine until it reaches the $curlResponse variable. From there onwards, all the subsequent variables ($xmlObj, $translatedStr, $translatedText) appear to be empty ...

The ultimate guide to loading multiple YAML files simultaneously in JavaScript

A Ruby script was created to split a large YAML file named travel.yaml, which includes a list of country keys and information, into individual files for each country. data = YAML.load(File.read('./src/constants/travel.yaml')) data.fetch('co ...

Creating experiences for websites controlled by gestures

It's been a great experience working on a website that utilizes gesture-based technology. My inspiration for this project came from various sources, including this link. Despite researching extensively through websites, Google, Wikipedia, and GitHub, ...

Unexpected rendering of data retrieved by React

I'm currently facing a challenge with the display of data using ReactJS. Although I can successfully retrieve data from the API and iterate through each object to display individual "products", I'm encountering a problem where each of the thirte ...

Leveraging useContext to alter the state of a React component

import { createContext, useState } from "react"; import React from "react"; import axios from "axios"; import { useContext } from "react"; import { useState } from "react"; import PermIdentityOutlinedIcon f ...

displaying the local path when a hyperlink to a different website is clicked

fetch(www.gnewsapi.com/news/someID).then(response => newsurl.href = JSON.stringify(data.articles[0].url) fetch('https://gnews.io/api/v3/search?q=platformer&token=642h462loljk').then(function (response) { return response.json(); }).th ...

Guide on how to beautify HTML and generate output files in the identical directory as the current one

Hey there! I'm currently working as a junior front-end developer and have recently delved into using gulp. One of the challenges I face is dealing with HTML files received from senior developers that aren't well-formatted, containing excessive wh ...

Navigate to the chosen item in material-ui scroll bar

Currently, I have a list created using material-ui which contains numerous items and displays a scrollbar due to its size. I am looking for a way to automatically scroll to the selected item within the list. Does anyone have any suggestions on how I can a ...

How can I substitute a specific portion of a string with values that correspond to items in an object array?

I am currently working on a task that involves extracting values from objects in a string to perform mathematical operations. While I have managed to retrieve the data and match the values enclosed in brackets, I am facing a roadblock in terms of what step ...

Clicking to close tabs

I am currently working on implementing a tab functionality on my website and I want these tabs to be responsive. Here is the code snippet I have been using: function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.ge ...

Is it possible to verify the existence of several arrays of data in a MongoDB database using Node.js?

I'm trying to verify if certain data exists in a database. If the data does exist, I want to set the value of k to 1. global.k = 0 let roll = {roll0:"1616",roll1:"234"} for (let i = 0; i < inputcount; i++) { let obj1 = roll["roll" + i]; const ...

JavaScript Routing with Multiple Files

I tried to access api.js from Routes.js, but I encountered an issue stating that the function my_function_in_api is not defined. Here is my code, could you please help me identify where the problem lies: Routes.js var val = require('file name') ...

Having trouble showing the text on the screen, but after checking my console, I notice empty divs with p tags. Surprisingly, the app is still functioning properly without any

Currently, I am developing a joke app entirely on my own without any tutorials. One of the components in the app is SportsJokesApi, which retrieves data from a local json folder (SportsJokesData) that I have created. Here is how it is structured: const Sp ...