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

When I attempted to run `npm start`, an error with status code 1 was thrown,

Upon running npm start, the following error is displayed: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d4c5d5d6d1d031c031d">[email protected]</a> start /Users/user/Desktop/react-tutorial > react-script ...

Uncaught Node.js Error Event Handling

Hello everyone, I'm new to this and currently working on writing a code that utilizes node's event emitter. Take a look at the code snippet below: var EventEmitter = require('events').EventEmitter; var errors = require('./errors&a ...

What are some ways to optimize the use of the jquery.mCustomScrollbar.js script?

I have a myriad of inquiries and would greatly appreciate your assistance in addressing them. Despite spending countless hours attempting to solve the issue independently, I have been unsuccessful. One question that plagues me is why, when using Google Ch ...

What are some ways to leverage a promise-returning callback function?

Here is a function that I have: export const paramsFactory = (params: paramsType) => { return ... } In a different component, the same function also contains await getPageInfo({ page: 1 }) after the return .... To make this work, I need to pass a cal ...

Utilizing vue-router to create two separate navigation bars where only one link is highlighted as active

In my setup, I have implemented two sections with navigation structured as follows: <ul class="navigation-list"> <li v-for="(route, index) in navRoutes"> <router-link :to="route.path"> <span>{{ route.name }}</span> ...

Error encountered when URLSearchParams attempts to add an array

Hi, I'm encountering a problem when attempting to send an array using URLSearchParams. Here is the code snippet in question: const worker = async(endpoint, method, parameters) => { let body; if (typeof parameters === 'object' &am ...

Tips on slowing down the Jquery UIBlock Plugin

Currently, I am implementing a plugin found at http://jquery.malsup.com/block/#overview. However, I am interested in configuring the blockUI feature to only be displayed if an AJAX request takes longer than 1 second. Otherwise, I would prefer for nothing ...

Ensuring Consistency in Array Lengths of Two Props in a Functional Component using TypeScript

Is there a way to ensure that two separate arrays passed as props to a functional component in React have the same length using TypeScript, triggering an error if they do not match? For instance, when utilizing this component within other components, it sh ...

Frequent running of jQuery scripts

In my jQuery ajax code, I created a FitnessPlanDay: // Add Day ajax $('#addDay').on("click", function() { $.ajax({ url: '@Url.Action("AddDay")', type: 'POST', ...

Provide a response containing JSON data extracted from an HTML file

I am looking for a way to create a simple REST API using a hosting site that only allows hosting of HTML files along with JavaScript files. I want to be able to send POST/GET requests and receive JSON data in response. For instance, when making a GET requ ...

Validation of forms on the client side using Angular in a Rails application

I'm facing an issue with implementing client-side validations for a devise registration form using Angular. Although I am able to add the "invalid" class to the fields as expected, I am struggling to get any output when using ng-show. There are no oth ...

Failed to convert value to a string

I'm dealing with a frustrating issue and I just can't seem to figure it out. The error message I'm getting is Cast to string failed for value "{}" at path "post". { "confirmation": "fail", "message": { "message": "Cast to string fai ...

Guide to executing API PATCH request on the server for a system that approves outings?

I have developed a system for approving outings using the MERN Stack. I wrote code to change the leave status to "Approved", but the changes are not saved when I refresh the page. The PATCH request works fine through Postman. Mongoose Schema Snippet for l ...

What is preventing the control from being passed back from the PHP file to the AJAX success function?

My website is built using PHP, Javascript, and AJAX. Below is the essential code snippet: JS code (AJAX function): $("#btn_add_event").click(function(){ var strSeriaze = $( "#formAddEvent" ).serialize(); url = $( "#formAddEvent" ).attr('act ...

Getting Started with NodeJS Child Process for Electrons

My current challenge involves integrating a Gulp setup with debugging electron-quick-start. I am attempting to close and reopen Electron when changes are made to my source files using child_process.spawn. Launching the application seems to work fine, but w ...

Select all elements using jQuery that have an id attribute and belong to a specific class

I am attempting to select all items with an ID attribute that starts with a specified string while also having a particular class. For instance, consider the following: <div id="test-id-1" class="test"></div> <div id="test-id-2" class="test ...

Learning how to effectively incorporate two matSuffix mat-icons into an input field

I'm currently experiencing an issue where I need to add a cancel icon in the same line as the input field. The cancel icon should only be visible after some input has been entered. image description here Here's the code I've been working on ...

What is the best way to implement useAsync (from the react-async-hook library) using TypeScript?

Currently, I am utilizing react-async-hook to retrieve API data within a React component. const popularProducts = useAsync(fetchPopularProducts, []); The fetchPopularProducts() function is an asynchronous method used to make API calls using fetch: export ...

Setting the rotation position in JQuery prior to initiating the animation

Perhaps I could phrase my query differently as How can I rotate an image in JQuery from a starting position other than 0 degrees. I am attempting to animate the rotation of an image from -50deg to 0deg. However, regardless of what I do, JQuery seems to al ...

bespoke JavaScript confirmation dialogue box

After customizing a confirmation box for the logout feature, I encountered an issue. When the user presses cancel, the box closes and control remains on the same page as expected. However, when the user clicks yes to logout, nothing happens. Could anyone p ...