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

Steps for updating the property "project_id" within a nested JSON array to "project_name"

Issue: [ { "project_id": 1, "project_name": "CDP", "role": "PL" }, { "project_id": 2, "project_name": "Admincer", "role": "PM" }, I am trying to extract the "project_id" property from the above JSON array and add it to another array using a specific ...

What is the best way to determine if an item in an array is not empty?

Let's consider an array: arr = [{}, {}, {}, {}] If we want to determine the length of the array by counting only objects that contain at least one property, we can do this: [{}, {name: "Manchester United", odds: 3}, {}, {}] // 1 [{}, {name: "Liver ...

Avoid refreshing the page upon pressing the back button in AngularJS

Currently, I am working on building a web application that heavily relies on AJAX with AngularJS. One issue I am facing is that when the user clicks the back button on their browser, the requests are being re-made which results in data having to be reloa ...

Ways to effectively manage multiple asynchronous operations while retrieving emails and attachments using IMAP and JavaScript

Currently, I am utilizing the IMAP library along with JavaScript to retrieve emails from a server. This is my approach: Retrieve emails based on email address, subject, and a specified time frame. Determine the total number of emails received. For each e ...

Add empty objects to an array using a push function following the Vue JS constructor function

During my learning journey with Vue JS, I encountered an issue while attempting to populate an array with objects using a constructor function and the push method. Surprisingly, in Vue JS, the push function inserts a blank object into the array instead of ...

The error message "Data type must be consistent across all series on a single axis in Google Chart" may cause confusion

I'm struggling with an error message that appears when I try to run my Google chart. Here is the code I am using to generate the chart. function (resultVal) { var arrMain = new Array();//[]; for (var i = 0; i < resultVal.length; i++) { ...

Connect to the Kendo dropdown list undefined

I am looking to automatically bind a model to a Kendo dropdown list. The model is retrieved from the server and can sometimes be undefined or a valid object. My problem arises when the value is undefined. In this case, Kendo selects the first item in the ...

Correctly referencing a variable in a delayed AJAX request is crucial for ensuring the proper execution

I am facing an issue with a function called fetchAlbum. This function sets up a placeholder, sends an AJAX request, and updates the placeholder upon success. Here is the code snippet: function fetchAlbum() { albumCounter++; var albumElement = $(&a ...

Google Maps API now offers the ability to generate directions with up to 500 waypoints

I am facing a challenge with displaying a route on Google Maps using an array of 500 waypoints extracted from a GPS route. Google Maps is unable to create a direction or route with more than 23 waypoints, making it difficult to replicate the original GPS ...

The GIF Loader fails to animate while an AJAX request is in progress

Displaying a DIV element containing a loading GIF image while waiting for an AJAX call response. Initially, the DIV element is hidden. Upon clicking a checkbox, the loader DIV is shown, followed by the completion of the AJAX call, and then hiding the load ...

Highly complex regular expressions in nth-check causing inefficiencies during npm installation of react-router-dom

Feeling new and inexperienced with how to react, I attempted to execute the command "npm i react-router-dom" but it ended up stopping the download process and displaying several errors. In my search for a solution, I stumbled upon this reference to some ...

Substitute the ajax reply with the text currently displayed

I am facing an issue with the AJAX response in my HTML page. Currently, the response is being appended on top of the existing text instead of replacing it. Here is a snippet of my code: <html> <head> <h2>This is a test</h2> ...

The URL not functioning properly after including the .active class with JQuery

This website is built on the Shopify platform. To highlight an active link in a subcategory list, I am using JQuery and CSS to add the .active class to the element. However, after adding the JQuery code, the link element is not functioning properly and d ...

Is it possible to concurrently hot module reload both the server (.NET Core) and client (Angular)?

Using the command 'dotnet watch run' to monitor changes in server code and 'ng build --watch' for Angular code updates has been successful. It rebuilds the code correctly into directories "bin/" and "wwwroot/" respectively. myapp.cspro ...

AngularJS: Display the last four characters of a string and substitute the rest with 'X'

I am attempting to change the characters with X and make it look something like this XXXXXT123 This is what I have tried: var sno = 'TEST123'; alert(sno.slice(0,3).replaceWith('X')); However, I encountered an error in the console ...

Getting an input value dynamically in a React variable when there is a change in the input field

I am having an issue with my search text box. I need to extract the value onchange and send a request to an API, but when I try using the normal event.target method, it shows an error. How can I fix this? The problem is that onchange, I need to call a func ...

Analyzing objects within an array for similarities

Suppose I have an array containing objects: var arr = [ { id: 1, pt: 0 }, { id: 2, pt: 12 }, { id: 3, pt: 7 }, { id: 4, pt: 45 }, { id: 5, pt: 123 }, ]; I am looking to loop through this array (possibly using array.forEach or array.map) ...

Error in React Toaster preventing redirect with useHistory() before reaching another page

When I try to display a message using react toaster and then redirect to another page using history.push('/'), the toaster fails to work properly. Instead, the page immediately redirects to the homepage without displaying the toast message first. ...

Developing pagination functionality in ReactJS

I came across this piece of code in a forum (how to implement Pagination in reactJs): constructor() { super(); this.state = { todos: ['a','b','c','d','e','f','g','h ...

Inspecting Facebook links

Currently working on a website and interested in incorporating a feature similar to what Facebook has. I'm referring to the link inspector, but I'm not entirely sure if that's its official name. Allow me to provide an example to clarify my r ...