Issue
I am typescript learner and currently using the below logic to find if a string is having specific characters from an array. But it needs to be tuned I believe. Sorry if it looks a little dumb. Kindly help throwing some light on how to fix this.
myList.forEach((charac) => {
if (myString.includes(charac)) {
console.log("Error");
}
});
My input:
myList = [1,2,3]
myString = John1
Required output:
Error
UPDATE:
Considering I have the option of removing the error character, I modified my code like this:
myList.forEach((charac) => {
myString = myString.replace(errorCharacter, appConstants.EMPTY);
});
console.log(myString);
But this replaces only the first instance of errorCharacter. i.e
For John1
, I get a console output as John
.
But for John 111
, I get a console output as John11
.
I know we have to include /gi
to replace all. But don't know how to append the characters dynamically.
Adding like:
myString = myString.replace(errorCharacter + "/gi", appConstants.EMPTY);
didn't work as well.
Solution
Your code is correct if you use strings for your digits.
const myList = ['1','2','3']
const myString = "John1"
myList.forEach((charac) => {
if (myString.includes(charac)) {
console.log("Error");
}
});
A much cleaner way to write this would be:
const myList = ['1','2','3']
const myString = "John1"
const hasChar = myList.some((charac) => myString.includes(charac));
if(hasChar) {
console.log('Error');
}
Answered By - Matthieu Riegler
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.