3

I have following string tempalte:

const someUrl = `/${currentLocale}/somecategory/${category.get('slug')}/${post.get('iD')}/${post.get('slug')}`;

The problem is that this line is too long and I have to break it, but putting simple enter in the middle of it - causes with adding new line and extra whitespaces inside the generated string.

What is the best approach to break string template into few lines just for the code style purposes ?

hsz
  • 148,279
  • 62
  • 259
  • 315

3 Answers3

3

if you mean something like backslash in python, i'm afraid no, javascript doesn't have that.

i would recommend using + to combine multiple string segments. it's easier for you have the better-looking indent, something like:

const someUrl = `/${currentLocale}/somecategory/${category.get('slug')}` +
                `/${post.get('iD')}/${post.get('slug')}`;

or if you're using node, you may also consider util.format:

const util = require('util');

var template = '/%s/somecategory/%s/%s/%s';
var args = [currentLocale, category.get('slug'),
            post.get('iD'), post.get('slug')];

const someUrl = util.format(template, ...args);
iloahz
  • 4,491
  • 8
  • 23
  • 31
1

I find it quite difficult to read template strings that have lots of interpolation, like in your example.

Another way would be to create an array of each part and join them using Array#join:

const someUrl = '/' + [
    currentLocale,
    'somecategory',
    category.get('slug'),
    post.get('iD'),
    post.get('slug')
].join('/');
sdgluck
  • 24,894
  • 8
  • 75
  • 90
0

I'm not a fan of string concatenation. So I will suggest you to remove all the whitespace in that multiline template string.

const someUrl = `
  /${currentLocale}/somecategory/
  ${category.get('slug')}/
  ${post.get('iD')}/
  ${post.get('slug')}
`.replace(/\s+/g, '');
Lewis
  • 14,132
  • 12
  • 66
  • 87