Ciągi szablonów ES6 zapobiegają łamaniu linii

Mam długi ciąg znaków, który buduję za pomocą szablonów ES6, ale chcę, aby był bez podziałów linii:

var string = `As all string substitutions in Template Strings are JavaScript
              expressions, we can substitute a lot more than variable names.
              For example, below we can use expression interpolation to 
              embed for some readable inline math:`

console.log(string);

Wynik:

As all string substitutions in Template Strings are JavaScript
expressions, we can substitute a lot more than variable names.
For example, below we can use expression interpolation to
embed for some readable inline math:

Moje oczekiwania:

As all string substitutions in Template Strings are JavaScript expressions, we can substitute a lot more than variable names. For example, below we can use expression interpolation to embed for some readable inline math:
Author: Eugene Mihaylin, 2016-06-23

7 answers

To szaleństwo.

Prawie każda odpowiedź sugeruje uruchomienie funkcji runtime w celu poprawnego sformatowania, buildtime źle sformatowanego tekstu oO czy tylko ja jestem zszokowany tym faktem, szczególnie wpływem na wydajność ???

Jak stwierdził @dandavis, oficjalne rozwiązanie , (które btw jest również historycznym rozwiązaniem dla skryptów powłoki Uniksa), polega na ucieczce z powrotu karetki, dobrze, ze znakiem escape: \

`foo \
bar` === 'foo bar'

Proste, w tym samym czasie, w czasie rzeczywistym, w czasie rzeczywistym i w czasie rzeczywistym, w czasie rzeczywistym, w czasie rzeczywistym, w czasie rzeczywistym, w czasie rzeczywistym, w czasie rzeczywistym.]}

 104
Author: Cyril CHAPON,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-10-26 18:05:01

Łamanie linii to łamanie linii... Jeśli produkujesz je ręcznie, uważam, że masz je podczas uruchamiania.

BTW, na razie znajduję trzy obejścia:

  1. Skonfiguruj swój IDE lub edytor kodu tak, aby zawijał słowa, aby nie trzeba było dodawać podziałów linii w kodzie, jeśli ich nie potrzebujesz: edytor podzieli kod na dwie lub więcej linii, jeśli każde zdanie kodu wykracza poza skonfigurowane maksymalne znaki.

  2. Usuń podziały linii za pomocą String.prototype.replace:

var string = `As all string substitutions in Template Strings are JavaScript
expressions, we can substitute a lot more than variable names.
For example, below we can use expression interpolation to
embed for some readable inline math:`.replace(/\n/gm,"");

Uwaga: tutaj uruchamiasz funkcję runtime do sformatowania kodu buildtime , który może wyglądać jak anty-wzorzec i mieć wpływ na wydajność

  1. wykonaj te podziały linii kodu używając konkatenacji:
var string = `As all string substitutions in Template Strings are JavaScript`
              + `expressions, we can substitute a lot more than variable names.`
              + `For example, below we can use expression interpolation to` 
              + `embed for some readable inline math:`;
W moim przypadku wybrałbym opcję #1.
 32
Author: Matías Fidemraizer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-08 08:40:35

Jeśli masz ES6, możesz użyć tagów. Na przykład, znacznik stripIndent z biblioteki common-tags :

Zainstaluj przez:

npm install common-tags --save

Require via:

const stripIndent = require('common-tags/lib/stripIndent')

Użyj jako:

stripIndent`
  As all string substitutions in Template Strings are JavaScript
  expressions, we can substitute a lot more than variable names.
  For example, below we can use expression interpolation to
  embed for some readable inline math:        
`

Edit: Jak wspomniano w komentarzach, prawdopodobnie musisz wybrać tag: const oneLine = require('common-tags/lib/oneLine') dla pożądanego wyniku.

Więcej informacji o wyżej wspomnianym linku common-tags oraz na tym blogu

 22
Author: kvz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-20 08:42:12
  • Albo skonfiguruj IDE do tworzenia okładów i użyj szablonu string 1-liner, jak w pierwszym fragmencie kodu.

  • Albo użyj \ znaku przed przerwaniem linii.

    Przykład:

    const string = `1st line\
    2nd line\ 
    3rd line`; 
    

    Ale to nie uchroni Cię przed problemami z wyrównywaniem przestrzeni.

  • Albo użyj starej szkoły ES5 konkatenacji z '+'.

    Przykład:

    const string = '1st line' + 
                   '2nd line' + 
                   '3rd line'; 
    
  • Albo Użyj hack z szablonem pusty łańcuch var ${''}:

    Przykład:

    const string = `1st line${'' 
                   }2nd line${'' 
                   }3rd line`;
    

Pierwsza droga jest o wiele lepsza, bo:

  • mniej symboli (rozmiar)
  • no runtime operations (perfomance aspect)
 15
Author: Eugene Mihaylin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-11-14 15:23:14

Ja osobiście wolę wygląd łączenia tablicy zamiast:

var string = [
  `As all string substitutions in Template Strings are JavaScript`,
  `expressions, we can substitute a lot more than variable names.`,
  `For example, below we can use expression interpolation to`,
  `embed for some readable inline math:`
].join(' ');
 12
Author: jaybee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-24 01:43:36

W przypadku akapitów, możesz użyć wyrażenia regularnego \s+, Aby zastąpić białe znaki spacjami pojedynczymi spacjami, aby działały zarówno dla podziałów wierszy, jak i wcięć. Więc, w Twoim przypadku, po prostu dodaj .replace(/\s+/gm, ' ') na końcu.

var string = `As all string substitutions in Template Strings are JavaScript
              expressions, we can substitute a lot more than variable names.
              For example, below we can use expression interpolation to 
              embed for some readable inline math:`.replace(/\s+/gm, ' ');

console.log(string);
 2
Author: L. Holanda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-10-24 19:05:35

W ES6 wolę używać kombinacji dwóch najlepszych odpowiedzi tutaj (\ w połączeniu z .replace()). Korzyści płynące z połączenia funkcji replace ze znakiem escape oznaczają, że możesz utrzymać blokadę kodu konsekwentnie sformatowaną z resztą kodu.

/\s{2}/g jest wyrażeniem regularnym wybierającym dowolne wystąpienie dwóch lub więcej spacji.

const myMessage = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis id urna \
    ligula. Suspendisse lobortis ex ut vestibulum venenatis. Donec imperdiet ante odio, \
    nec malesuada diam tristique eget. Lorem ipsum dolor sit amet, consectetur adipiscing \
    elit. Cras in vulputate tellus.`
  .replace(/\s{2,}/g, "");

To wyświetla zwykły, nieprzerwany ciąg.

"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis id urna ligula. Suspendisse lobortis ex ut vestibulum venenatis. Donec imperdiet ante odio, nec malesuada diam tristique eget. Lorem ipsum dolor sit amet, consectetur elit. Cras in vulputate tellus."

 0
Author: mdawsondev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-10-24 19:05:54