-1

I'm trying to replace letters in a string based on an array of letters.

What I'm doing so far is

var value = '00-.Tday(52)'
if(!textService.containsLettersExcept(value, ['t', '.', '-'])){
    // yay
}

       function containsLettersExcept(text, exceptions){
            console.info('text before : ', text)
            for(var i = 0; i< exceptions.length; i++){
                var char = exceptions[i];
                text = text.replace(/char/gi, '');
            }
            console.info('text : ', text)
            return text.match(/[a-z]/i);
        }

This however tries to remove the string "char" rather than the variable char from the string text

Michael Tot Korsgaard
  • 3,892
  • 11
  • 53
  • 89

1 Answers1

3

Use the RegExp constructor:

text = text.replace(new RegExp(char, 'gi'), '');

Worth noting: some characters have special meaning and need to be escaped to be treated literally (for example . must be written as \. to mean "literal dot" and not "any character".

Alternatively, join the array of characters, escape what needs escaping, and perform the replacement once:

const exceptionsCharClass = exceptions
  .map(char => char.replace(/[\.\-\]\[]/, '\\$1')) // escape . - [ and ]
  .join('');                                       // join
const exceptionsPattern = `[${exceptionCharClass}]`
// exceptionsPattern is now [t\.\-], which you can use to replace once instead of in a loop.
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
  • How did you manage to convert the Wiki answer to a regular answer? Because of the diamond? – Wiktor Stribiżew Apr 05 '16 at 13:02
  • 1
    @WiktorStribiżew Yeah, diamond perks. The answer was starting to get non-trivial, so I reversed the community wiki. Normal users can custom flag their own answers to remove CW status and in 99.99% of the cases, mods will comply. – Madara's Ghost Apr 05 '16 at 13:04