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.