What is the best way to troubleshoot substrings for accurately reading URLs from an object?

While a user inputs a URL, I am attempting to iterate through an object to avoid throwing an error message until a substring does not match the beginning of any of the URLs in my defined object.

Object:

export const urlStrings: { [key: string]: string } = {
  'www.costco.com': '',
  'www.walmart.com': '',
  'www.google.com': '',
  'www.facebook.com': '',
}

During input, no error will be thrown until an incorrect substring is entered:

w
ww
www.
www.c
www.ca <--- this should throw error

However, due to setting subString as 1, only the first letter of the URL (item) is considered. The objective is to capture everything from the first letter to the increasing index, with a break statement to halt the for loop.

const correctUrl = (value: string | null): string => {
  let errorMessage = ''
  let item: string
  let subString = 1

  if (value && typeof value === 'string') {
    // eslint-disable-next-line guard-for-in
    for (item in urlStrings) {

      if (value?.length <= item?.length && subString <= item?.length) {
        if (item.substring(0, subString) === value.substring(0, subString)) {
          errorMessage = ''
          break
        }
      }
      subString += 1
    }
  } else {
    errorMessage = 'Throw error'
  }
  return errorMessage
}

Any recommendations? Also, note that this code is written in TypeScript.

Answer №1

Utilizing JavaScript's native array methods could simplify the task at hand. First, add the keys to an array and then utilize some to compare the strings with the input value. If none of them match, an error will be thrown.

const urlStrings = {
  'www.costco.com': '',
  'www.walmart.com': '',
  'www.google.com': '',
  'www.facebook.com': '',
};

const input = document.querySelector('input');
input.addEventListener('input', handleInput);

const validStrings = Object.keys(urlStrings);

function handleInput() {
  const { value } = this;
  const valid = validStrings.some(str => {
    return str.startsWith(value);
  });
  if (!valid) console.log('URL not valid');
}
<input type="text">

Answer №2

great inquiry!

To start, I suggest exploring guard clauses - your nesting is so deep that the logic becomes much harder to follow.

I believe your Throw error is connected to the incorrect if statement - basically, if it works at all, it will never throw the error. By implementing my initial recommendation and reformatting your code, the positioning should become clearer - and you can eliminate the need for a break statement.

Best of luck, feel free to ask further questions!

Answer №3

It might be simpler than you think. Utilizing array methods can easily solve this problem. First, create an array with the keys of the object (the URLs), then check if each URL does not begin with the specified text using the .every method. If none of the URLs match, return an error message.

const urlStrings = {
    'www.costco.com': '',
    'www.walmart.com': '',
    'www.google.com': '',
    'www.facebook.com': '',
};
const urls = Object.keys(urlStrings);
const correctUrl = (value: string | null): string => {
    if (value === null) {
        return 'Throw error';
    }
    return urls.every(url => !url.startsWith(value))
        ? 'Throw error' // None of the URLs matched
        : '';
}

The structure of the urlStrings object is peculiar. If the values in the object are unnecessary for your code, consider starting with a plain array instead.

const urls = [
    'www.costco.com',
    'www.walmart.com',
    'www.google.com',
    'www.facebook.com',
];

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

I want the navigation bar to appear only upon scrolling, but when I refresh the page it is already visible, and then vanishes as I start scrolling

I'm working on a project where I want the navigation bar to only appear after scrolling a certain distance down the page. However, I've noticed that when I refresh the browser, the navigation bar appears immediately and then disappears once I sta ...

Searching for two variables in an API using TypeScript pipes

I'm stuck and can't seem to figure out how to pass 2 variables using the approach I have, which involves some rxjs. The issue lies with my search functionality for a navigation app where users input 'from' and 'to' locations i ...

Struggling to display a chart using angular-chart

I am facing an issue with rendering my chart. I have followed the instructions provided on the GitHub page of angular-chart.js. I have created a plunker to showcase my problem: http://plnkr.co/edit/x7XJhxxvYMzWr3u7lBcJ?p=preview Although I can access and ...

The functionality of the .toggle method is limited to only being effective 1.5

I'm having an issue with making an image popup using the .toggle function in javascript. It seems to work initially, but then only works partially after that. When I click on the image, it opens as expected. However, when I try to close it by clickin ...

Steps to eliminate the select all checkbox from mui data grid header

Is there a way to remove the Select All checkbox that appears at the top of the checkbox data column in my table? checkboxSelection The checkboxSelection feature adds checkboxes for every row, including the Select All checkbox in the header. How can I ...

Angular 9 Singleton Service Issue: Not Functioning as Expected

I have implemented a singleton service to manage shared data in my Angular application. The code for the service can be seen below: import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataS ...

Avoiding leaps through the use of dynamic pictures?

Currently, I am implementing the picture element along with srcset to download the same image but in varying resolutions depending on the screen size of the device. The image has a style of max-width: 100%, causing it to shift the content below when downl ...

Tips for overlaying text on the background in Next.js:

I'm currently working on creating an image element with overlay text. Check out my jsx code below: <div className={styles.img}> <img src={src} alt="" /> <p>{`(${size})`}</p> </div> And here is t ...

Ways to ensure the bootstrap table header width aligns perfectly with the body width

I am having an issue with my bootstrap table where the header width is smaller than the body width because I set the table width to auto. How can I align the header and body widths? Here is a link to a plunker showcasing the problem. https://plnkr.co/edit ...

Exploring the best practices for loading state from local storage in VueJS/NuxtJS by leveraging the "useLocalStorage" utility

When attempting to utilize useLocalStorage from pinia, I am encountering an issue where the data in the store's state is not fetched from local storage and instead defaults to the default value. Below is the code snippet from my store method: import ...

Error: Unexpected character encountered

When attempting to parse an array of objects enclosed in double quotes, I encountered an error: Uncaught SyntaxError: Unexpected token ' var test = "[{'key' :'D', 'value': 'Deceased Date'},{'key' ...

Instantiate a fresh Date object in JavaScript by passing in my specific parameter

Check out this code snippet: $(function () { var timestamp = 1443563590; //Tue, 29 Sep 2015 21:53:10 GMT var today2 = moment.unix(timestamp).tz('America/New_York').toString(); alert(today2); //var dateinNewYork = new Date(wh ...

Modify the URL and show the keyword utilized in a search module

Does anyone know how to update the URL in a search bar? I'm using Redux to display search results, but the URL remains the same. How can I make the URL show the keyword being searched, like this: http://localhost/seach?q=keyword ...

Updating the index page with AJAX in Rails 4: Step-by-step guide

It's surprising that I haven't found answers to my specific questions despite searching extensively. I have an Expenses page where I want to display all expenses for a given month in a table. Currently, I achieve this by adding month and year par ...

Verify information and send messages using JavaScript validation

I need assistance with my HTML form and JavaScript code. I am trying to send a parameter from the form to JavaScript in order to check if the input matches any values in an array. If there is a match, I want an alert message to be sent. However, the issue ...

Unable to retrieve data from the database within PHP code

I have successfully built a shopping cart website utilizing SQL, HTML, and PHP. Below is the code snippet for the 'Add to Cart' button: <form method="post" action="cart.php" class="form-inline"> <input type="hidden" value="&apos ...

Encountering a compiler error due to lack of patience for a promise?

In the current TypeScript environment, I am able to write code like this: async function getSomething():Promise<Something> { // ... } And later in my code: const myObject = getSomething(); However, when I attempt to use myObject at a later po ...

The function Object.defineProperties() allows for reassigning a property's value after it has been initially

The issue arises in the initial code snippet provided below, specifically when dealing with the object book. Initially, the value of book.year is set to 2013. Even after updating the value by setting book.year = 2015, retrieving the value using book.year s ...

Having trouble retrieving json data from PHP page using jQuery $.ajax

Having trouble accessing this JSON data in JavaScript, as when I try to alert it the result comes back as undefined Below is the jQuery code snippet: $.ajax({ type: "POST", url: "frmMktHelpGridd.php", data: { labNo: secondElement ...

Transferring a parameter from link_to to a popup window in a Rails application

I am facing an issue with passing an object to my modal in Rails. The object has a table of results with an attribute "email", but I seem unable to pass it so that I can use it within my modal. index.html.erb <div class="modal fade bs-example-modal-lg ...