Skip to content

Commit

Permalink
fix: do not concatenate string literals
Browse files Browse the repository at this point in the history
  • Loading branch information
snitin315 committed Oct 29, 2021
1 parent 97db466 commit 35ee14a
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
6 changes: 3 additions & 3 deletions lib/rules/prefer-template.js
Expand Up @@ -202,11 +202,11 @@ module.exports = {
}

if (isConcatenation(currentNode) && !hasIdentifierReference(currentNode)) {
const nodeTexts = sourceCode.getText(currentNode).split("+");

// As there are no varibales used in this concatenation, we can sipmly calculate the concatenated string
const concatenatedText = sourceCode.getText(currentNode).split("+").map(e => e.trim().slice(1, -1)).join("");
nodeTexts[nodeTexts.length - 1] = ` \`${nodeTexts[nodeTexts.length - 1].trim().slice(1)}`;

return `\`${concatenatedText}\``;
return nodeTexts.join("+");
}

if (isConcatenation(currentNode) && hasStringLiteral(currentNode) && hasNonStringLiteral(currentNode)) {
Expand Down
24 changes: 18 additions & 6 deletions tests/lib/rules/prefer-template.js
Expand Up @@ -227,25 +227,37 @@ ruleTester.run("prefer-template", rule, {

// https://github.com/eslint/eslint/issues/15083
{
code: "\"Hello \" + \"world \" + test",
output: "`Hello world ${ test}`",
code: "'a' + 'b' + foo",
output: "'a' + `b${ foo}`",
errors
},
{
code: "'a' + 'b' + foo + 'c' + 'd'",
output: "'a' + `b${ foo }c` + `d`",
errors
},
{
code: "var foo = \"Hello \" + \"world \" + \"another \" + test",
output: "var foo = `Hello world another ${ test}`",
output: "var foo = \"Hello \" + \"world \" + `another ${ test}`",
errors
},
{
code: "'Hello ' + '\"world\" ' + test",
output: "'Hello ' + `\"world\" ${ test}`",
errors
},
{
code: "\"Hello \" + \"'world' \" + test",
output: "`Hello 'world' ${ test}`",
output: "\"Hello \" + `'world' ${ test}`",
errors
},
{
code: `"default-src 'self' https://*.google.com;"
+ "frame-ancestors 'none';"
+ "report-to " + test + ";"`,
output: "`default-src 'self' https://*.google.com;frame-ancestors 'none';report-to ${ test };`",
+ "report-to " + foo + ";"`,
output: `"default-src 'self' https://*.google.com;"
+ "frame-ancestors 'none';"
+ \`report-to \${ foo };\``,
errors
}
]
Expand Down

0 comments on commit 35ee14a

Please sign in to comment.