How to determine if a string includes a particular substring in Javascript without using the indexOf method

Is it possible to determine if a string contains a specific substring without using indexOf, regex match, or any standard JavaScript methods?

Feel free to review this code snippet on jsfiddle: https://jsfiddle.net/09x4Lpj2/

var string1 = 'applegate';
    var string2 = 'gate';

    function checkSubstring(string1, string2){
  var j = 0;
      var k = 0;
      var contains = 'false';
      var charArray1 = string1.split('');
      var charArray2 = string2.split('');
  
      for(var i = 0; i < charArray2.length; i++){
      j = i;
        if(charArray1[j++] != charArray2[k++]){
      contains = 'false';
        }else{
      contains = 'true';
        }   
      }
  
     console.log(contains);
    }
checkSubstring(string1, string2);

This approach works only when the indexes of the characters in both strings align (e.g., comparing "applegate" and "apple"). However, it fails when the indexes are not the same (e.g., comparing "applegate" and "gate"). How can the iteration values be manipulated to ensure accurate results in both scenarios?

Answer №1

Give this revised script a shot.

var str1 = 'pineapple';
var str2 = 'apple';
var str3 = 'pine';
var str4 = 'ear';

function containsSubstring(str1, str2){
  var chars1 = str1.split('');
  var chars2 = str2.split('');
  var matchCount = 0;

  for(var x = 0; x < chars1.length - chars2.length + 1; x++){
    matchCount = 0;
    for(var y = 0; y < chars2.length; y++){
      if(chars1[x+y] == chars2[y]){
        matchCount++;
        console.log(x, y, matchCount, chars1[x+y], chars2[y]);
      } else {
        console.log(x, y, matchCount, chars1[x+y], chars2[y]);
        break;
      }
      if(matchCount == chars2.length){
        return true;
      }
    }
  }
  return false;
}

console.log(containsSubstring(str1, str2));
console.log(containsSubstring(str1, str3));
console.log(containsSubstring(str1, str4));   
console.log(containsSubstring(str1, str5)); 
console.log(containsSubstring(str4, str1)); 

Answer №2

Greetings from the world of programming. Regular expressions can come in handy, unless they are also not allowed.

function checkSubstring(mainString, subString) {
    console.log(mainString.includes(subString) ? "Found" : "Not Found");
}

Explore Regular Expressions

Answer №3

The existing code has a flaw in its logic – it only checks if the last character of string A is equal to the corresponding character of string B. Perhaps the following revised version of the code is what you are looking for, which includes an additional line of code:

var string1 = 'applegate';
var string2 = 'gate';

function containsString(string1, string2){
  var j = 0;
  var k = 0;
  var contains = 'false';
  var charArray1 = string1.split('');
  var charArray2 = string2.split('');

  for(var i = 0; i < charArray2.length; i++){
    j = i;
    if(charArray1[j++] != charArray2[k++]){
      contains = 'false';
      break;
    }else{
      contains = 'true';
    }   
  }

  console.log(contains);
}

// Additional line of code here

Answer №4

Try this solution without relying on any built-in functions

function customSubstringSearch(longString, shortString){
var count = 0;
for(var i = 0; i < longString.length; i++){
  for(var j = 0; j < shortString.length; j++){
    if(shortString[j] != longString[i + j]){
      break;
    }
    if((j+1) == shortString.length){
      count++;
    }
  }
}
return count;
}

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

Having trouble retrieving JSON data from an external URL in AngularJS when making a $http.get call and using the success method?

Code in the Controller.js file: let myApp=angular.module('myApp',[]); myApp.controller('myController', function($scope,$http){ $http.get('data.json').success(function(data){ $scope.art=data; }); }); ...

Numerous asynchronous requests

I'm trying to figure out why the application keeps making multiple ajax calls. Check out this directive: gameApp.directive('mapActivity', function() { return { restrict: 'A', link: function(scope, element, att ...

What potential factors could lead to an MUI Snackbar failing to produce the accurate class names?

I am facing an issue with displaying notifications on my Gatsby blog whenever the service worker updates. I am using a MUI Snackbar toast for this purpose. However, sometimes the styling of the toast is not applied correctly and it ends up looking like thi ...

Avoid including package-lock.json file in GitHub contribution history

After the release of npm v5.0.0, utilizing npm packages automatically generates a package-lock.json file when running npm install. In my situation, my package-lock.json document is almost 10,000 lines long. Npm advises that this file should be committed: ...

Node.js video tag requests minimal data transfer on mobile devices

After creating a node server for streaming mp4 videos from a Mongo database using gridfs, I encountered an issue. The videos stream perfectly to desktop browsers, but when attempting to stream to a mobile device, the video player shows up, but the video do ...

Having trouble getting the Angular 2 quickstart demo to function properly?

Just starting out with Angular 2, I decided to kick things off by downloading the Quickstart project from the official website. However, upon running it, I encountered the following error in the console: GET http://localhost:3000/node_modules/@angular/ ...

Styling nested divs in CSS

I am experiencing an issue where the child divs within parent divs are overflowing outside of the parent divs. To get a better understanding of the problem, please try running the code below in a browser: My goal is to align the innermost divs horizontall ...

Reactjs, encountering a hitch in utilizing material UI: Incompatible hook call detected

As a newcomer to React, I decided to incorporate Material UI components into my project. After installing the components locally using npm install and importing them into my project, I encountered an error when trying to run start: Error: Invalid hook call ...

Storing User IP Address in Database with Express and Mongoose

I'm looking for a way to store users' IP addresses in mongoDB by using a mongoose model file for the user. Does anyone have any suggestions on how I can achieve this? Here is an example of the schema for the Users module file: const userSchema ...

JS: Looking to add animation with a button click?

Looking for feedback on my code to animate/colorify the div when clicking the 'Animate' button. Any suggestions or additional code are welcome! This is how my code currently looks: .anime { animation: coloranimate 5s; width: 100px; heig ...

Node 14 introduces a new feature that allows modules to be imported using absolute paths for native ES6 modules

As I develop an app in node version 14.9.0, the need for importing modules arises. To make the process cleaner and more organized, I have configured my ES6 module with "type": "module" in my package.json. My goal is to implement absolut ...

conceal or reveal a button based on the authentication status of a user in a

I'd like to display a "Become Tutor" button if either: 1. The user is not logged in. 2. The logged-in user is not already a tutor. Otherwise, I want to show the "Tutor Dashboard" button for users who are already tutors. While my code is functional, i ...

What is the reason behind the image not displaying before the AJAX request is initiated and then disappearing once the request is completed?

I am attempting to display a "loading" gif while my AJAX request is being processed. Below are the functions I am using: beforeSend: function () { $('.form-sending-gif').show(); console.log("The beforeSend function was called"); } and ...

Retrieve the Latest Information from the Asp.Table

My table setup is as follows: <asp:Table ID="model" runat='server'> <asp:TableRow> <asp:TableHeaderCell class="col-xs-2"> Name </asp:TableHeaderCell> <asp:TableHeaderCell class="col- ...

The Next.js Link feature does not always guarantee that the component will render correctly, and the serverSideProps function may not always receive updated

Having an issue with next.js - when a user tries to navigate from one profile to another using the Link in the navbar: <li> <Link href={`/profile/${user.user.id}`}> <a className="flex flex-row items-center"> ...

Connecting a string array to the navigation bar

Need Assistance with AngularJS: In my controller, I have a string array that looks like this: var app = angular.module('myApp', []); app.controller('mycontroller', function($scope) { $scope.menuitems =['Home','About&apos ...

Passing input parameters from a jQuery dialogue box to a handler file (.ashx) in ASP.NET: A step-by-step guide

Hey everyone! I've set up a jQuery dialog box with two input fields as shown below: <div id="dialog" title="Login"> <form action="" method="POST" id="loginForm"> Username: <input type="text" name="username" /><b ...

Guide on serving static HTML files using vanilla JavaScript and incorporating submodules

Is it possible to serve a static html file with elements defined in a javascript file using imports from submodules using vanilla JS? Or do I need bundling tools and/or other frameworks for this task? Here's an example code structure to showcase what ...

Creating a clickable image link on a website using JavaScript: Tips and tricks

I'm looking to implement a specific feature on a website using JavaScript: <a href="URL"><img src="IMG_URL"></a>. I believe there are three key steps involved: When the site loads, JavaScript will send a request (possibly through a ...

When JavaScript evaluates special characters in HTML, it interrupts the function call within an AJAX response

Recently, I have been developing a custom form completion feature for a website/tool that I am working on. After successfully implementing the search functionality, which displays results below the input field, I wanted to enable users to select a result ...