Search code examples
javascripteslinteslintrc

ESLint rule to prevent string from appearing in string or template literal


I'd like an ESLint rule to prevent the string "foo" from appearing anywhere in strings or template literals, so both statements would be in violation:

const str1 = 'foo bar';
const str2 = `foo ${bar}`;

I configured no-restricted-syntax to handle strings, handling str1 from the example above,

'no-restricted-syntax': [
    'error',
    'Literal[value=/foo/]',
],

, but what's the equivalent syntax to handle template literals?


Solution

  • The selector syntax would be TemplateElement[value.cooked=/foo/] (demo), e.g.

    'no-restricted-syntax': [
        'error',
        'Literal[value=/foo/]',
        'TemplateElement[value.cooked=/foo/]',
    ],
    

    Contrasted with a Literal node, a TemplateElement's value is an object with two properties: cooked (similar to Literal[value]) and raw (analogue of Literal[raw]).