JavaScript substring() function in clone is experiencing an error

I am currently working on a JavaScript function that determines whether a specific substring is present in a larger main string. For instance, if the main string is "111010" and the substring is "011," the expected result should be false since the substring does not exist within the main string. However, my code is returning true instead. Below is the snippet of the code:

var string = "111010",
substr = "011";     

var found=false;

outter:for(var i=0;i<string.length;i++){
    if(string.charAt(i)==substr.charAt(0)){                   
        var k=i+1;
        inner:for(j=1;j<substr.length;j++){
            if(string.charAt(k++)==substr.charAt(j)){
                found=true;
                continue inner;
            }else{
              continue outter;
            }
        }
    }
}

if(found!=false){
    console.log("y")
}else{
    console.log("n");
}

Answer №1

Ensure you always re-initialize the found variable before each iteration.

var string = "111010",
substr = "0110";     

var found=false;

for(var i=0;i<string.length;i++){
    if(string.charAt(i)==substr.charAt(0)){                   
        var k=i+1;
        for(j=1; j < substr.length;j ++)
            if(string.charAt(k++)==substr.charAt(j)){
                found=true;
            }else{
               found = false; // <<--this
               break;
            }
        if(found) break;   
    }
}

if(found!=false){
    console.log("y")
}else{
    console.log("n");
}

Your code will return true if a common letter between your string and substring is found, fix this issue.

Avoid using labels in your code as they are not recommended. Thank you!

See the correct implementation of your code here.

var found = false;

for (var i = 0; i < string.length; i++) { // starting position
    found = true; // All letters match, prove otherwise

    for (j = 0; j < substr.length; j++) { // Compare the given string with the string starting at i
        if (string.charAt(i + j) != substr.charAt(j)) { // If one letter does not match, stop searching
            found = false;
            break;
        }       
    }

    if (found) break;
}
  • Avoid treating the first letter separately
  • Avoid using labels
  • Focus on finding non-matching letters instead of direct matches
  • Avoid unnecessary index variables like k, use j for needle position and i+j for hay position

Answer №2

Here is a snippet of code that demonstrates how to check for a specific substring within a string:

var mainString = "this is an example string", subString = "example";
var result = mainString.indexOf(subString);

if (result >= 0) { 
    alert('The substring exists in the main string.');
} else {
    alert('The substring does not exist in the main string.');
}

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 use jquery to specifically target classes?

I am trying to achieve the following: $('.class.img').css('cellpadding', variable); However, this code does not seem to be working as expected. Despite searching online, I have not been able to find a solution. Any assistance on how to ...

Sending numerous data fields via ajax

Here is a link to my code playground: http://jsfiddle.net/barmar/mDfQT/10/ $('.add_options').on('click', function () { $('#variants').append('<div class="some_id"><input type="text" id="prop_name" class=" ...

Using the IE method getelementbyid to target an object within the document

Is there a way to use getElementById to access an object that already exists in the document? I am specifically trying to target the element "test" which is nested within parentDiv1. While this code works in Firefox, it's not functioning properly ...

Is there a way to block the .load() function directly from the browser console?

I am looking to enhance the user experience on my website by dynamically loading certain content after login. This involves using a $.post(...) method to interact with a servlet that verifies the user's credentials, followed by a $.load(url) function ...

Explore RxJs DistinctUntilChanged for Deep Object Comparison

I have a scenario where I need to avoid redundant computations if the subscription emits the same object. this.stateObject$ .pipe(distinctUntilChanged((obj1, obj2) => JSON.stringify({ obj: obj1 }) === JSON.stringify({ obj: obj2 }))) .subscribe(obj =& ...

Retrieving external JSON data with JavaScript

I am attempting to utilize a specific service for proxy checking. They offer an uncomplicated API that delivers JSON data. My goal is to retrieve this JSON on my own server. Despite various attempts, I consistently encounter either a CORS request issue or ...

Issue with MongoDB find() function not retrieving any results (Assignment)

I am currently working on an assignment that requires the use of noSQL databases. Although I understand most of the queries we have to perform in mongoDb, every query I execute seems to return a blank result. Initially, we are required to create a collect ...

Discover the power of AngularJS's ng-route feature for creating a dynamic and seamless one-page HTML template experience

I'm attempting to create a dynamic header using ng-repeat. Here's the initial code: <ul class="right"> <li><a href="#carousel">Home</a></li> <li><a href="#about-us">About Us</a></li> &l ...

Updating or swapping images using JavaScript and HTML

I am looking to implement a feature similar to Twitter, where uploading a picture automatically updates the avatar by displaying a spinner while the new image loads. I attempted to accomplish this with the following code: <script language="javascript"& ...

Enzyme locates and chooses the initial occurrence of an element

I am attempting to simulate a click on the initial box out of three. My React script appears as follows: const Boxes = (props) => { return ( <div className="container"> <div onClick={props.showMessage} className="box">One& ...

Encountering difficulty importing TypeScript files dynamically within a Deno executable

When attempting to import a file from aws in an exe using its public link based on user input, I am facing difficulties For example, I generated my exe with the command below deno compile --allow-all main.ts Users execute this exe using commands like ./e ...

"Trouble arises when event listener fails to function following an append operation

Recently, I delved into the world of HTML/CSS and jQuery in an attempt to create a simple web game. Below is a snippet of my HTML code: function playGame() { var theLine = "<div id = \"line\">"; for (var i = 0; i < 9; ...

jQuery is not updating the div as expected

While typing out this question, I'm hoping to uncover a solution that has eluded me so far. However, just in case... About a year ago, I successfully implemented something similar on another website and went through the code meticulously. Surprisingl ...

Reserve a spot for a credit card in 4-digit format with VueJS

When I enter a credit card number, I want to automatically insert a space after every 4 digits. For example: 0000 0000 0000 0000 I am currently using vue js and have come across examples using jquery, but I prefer not to use jquery. Any help would be appr ...

Is it possible to move the res.send() outside of the function in node.js?

I currently have the following code: var server = http.createServer(function(req,res){ res.writeHead(200,{'Content-Type': 'text/html; charset=utf-8'}); var oo = require('/test.js'); oo(connection, function (e, res ...

Angular.js and ExpressJS combination results in a 404 error for a POST request

Currently, I am attempting to make a request to my ExpressJS server using AngularJS: angular.module('app').controller('contactCtrl', function($scope, $http) { $scope.envoyer = function(nom, organisation, courriel, telephone, messag ...

The interface vanishes upon the integration of TinyMCE into the module

Currently, I am working on a project using Angular-fullstack and attempting to integrate ui-TinyMCE. However, I encountered an issue when I made the following changes: angular.module('academiaUnitateApp') .controller('NewEntryCtrl', ...

Notify immediately if there is any clicking activity detected within a designated div container

I am looking to trigger an alert when a specific div is clicked. Here is the scenario: <div class="container"> <div class="header"> <h1>Headline<h1> </div> <div class="productbox"></div> </div> I have succ ...

Access remote web page within bootstrap modal

Dealing with a recurring issue, I am trying to create a modal that opens content from a remote page populated by a MySql database. Custom styling is also required for the modal. Progress has been made, but now I'm stuck. Below is the current code: Ou ...

Updating a property in an object within an Angular service and accessing it in a different controller

I am currently utilizing a service to transfer variables between two controllers. However, I am encountering difficulties in modifying the value of an object property. My goal is to update this value in the first controller and then access the new value in ...