AnnaSm
AnnaSm

Reputation: 2300

ESLint error about Unexpected String Concatenation

I have the following:

return (useWordBoundary ? subString.substr(0, subString.lastIndexOf(' ')) : subString) + '\u2026';

Eslint is rejecting my code saying:

Suggest using template literals instead of string concatenation. (prefer-template)

What is wrong with the above?

Upvotes: 1

Views: 14188

Answers (5)

Partha S. Kundu
Partha S. Kundu

Reputation: 1

In my case I found it useful for not only template related variables but also scripting variables as well, like: I was getting this error for a concatenation as it was like this:

   if ($('#' + data.id_field).children().length === 0) {
  $(e.target).prepend($(e.target), ContactWrapper);
}

So I fixed it by using like this:

    if ($(`#${data.id_field}`).children().length === 0) {
  $(e.target).prepend($(e.target), ContactWrapper);
}

Hope this example helps!

Upvotes: 0

Gil Perez
Gil Perez

Reputation: 1125

Here is a different example using eslint error: Unexpected string concatenation | prefer-template:

(YES)

const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);

vs

(NO)

const value = '; ' + document.cookie;
const parts = value.split('; ' + name + '=');

Upvotes: 0

TimoStaudinger
TimoStaudinger

Reputation: 42500

It's a style question really. In your example, there's arguably not a lot of benefit in using template literals:

return `${useWordBoundary ? subString.substr(0, subString.lastIndexOf(' ')) : subString}\u2026`;

In other situations, it makes code more readable:

return `Hello, ${name}!`;

// vs.

return 'Hello, ' + name + '!';

If you choose to, you can selectively disable a rule for a specific line via a comment:

// eslint-disable-next-line prefer-template
return (useWordBoundary ? subString.substr(0, subString.lastIndexOf(' ')) : subString) + '\u2026';

Upvotes: 10

Ele
Ele

Reputation: 33726

Template literals are also known as String Interpolation.

Your code must follow this syntax:

return `${(useWordBoundary ? subString.substr(0, subString.lastIndexOf(' ')) : subString)} '\u2026'`;

See? isn't necessary to concatenate using + operator.

var greeting = "Hello";

var completeGreeting = `${greeting} World!`;

console.log(completeGreeting);
See? the string is built using the parameters within this expression: ${}

Resource

Upvotes: 4

Sidney
Sidney

Reputation: 4775

Based on that rule's documentation it simply flags any string concatenation with +. Instead, it suggests using ES6 template literals. Here's how you'd do that in your code:

return `${(useWordBoundary ? subString.substr(0, subString.lastIndexOf(' ')) : subString)}\u2026`;

You can read more about template literals here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Upvotes: 1

Related Questions