Home > Enterprise >  Check if string contains a character from list - Typescript
Check if string contains a character from list - Typescript

Time:03-08

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.

CodePudding user response:

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');
}

CodePudding user response:

You can use the split method, which when given a character, will split a string up by that character, but, when given an empty string it will split it my character.

Also the includes method on arrays returns a boolean for whether that given value exists in the array. Also, your number might be causing an issue, so you can cast it by adding it to an empty string. So together

let str = "John1"
arrayOfValues.forEach(cantContain => {
   if(str.split('').includes(cantContain   "")) {
      // your code
   }
});

CodePudding user response:

Answering based on your updated question.

You can use replaceAll() instead of replace().

As you've pointed out replace() method replaces only the first occurrence so since you want to replace all the occurrences replaceAll() should work for you.

  • Related