What is the purpose of String.raw in Javascript?

7

Well, the question is the same.

I would like to know what the String.raw method in Javascript is for.

I saw something in the MDN documentation, but I did not quite understand the use

Is it related to string templates ?

    
asked by anonymous 22.06.2018 / 21:33

3 answers

9

The String.raw is to avoid escaping strings like:

  • \n
  • \r
  • \x01
  • \u000A
  • \n

That is, if you do this:

console.log('foo\nbar');

It will show a line break, but if you do this:

console.log(String.raw'foo\nbar');

It will show exactly r , I believe that the main utility of this is to send via JSON, for requests (HTTP or not) without the escape, since in JSON that usually handles this is the interpreter at the time of "reading ".

This is similar to % of% used in Python , for example in Python2:

#string escapada
print 'Foo\nbar'

#string literal
print r'Boo\nbaz'

This will be displayed:

Foo
bar
Boo\nbar

Or as @ in C #:

//string escapada
Console.WriteLine("Foo\nbar");

//string literal
Console.WriteLine(@"Boo\nbaz");

Answering the specific question:

  

Do you have any relation to the string templates?

It has a relation, yes, because String.raw only works with string templates , with string, it will not work with "..." or single '...' , only with the serious accent, which in JavaScript is the string template:

'....'

As already well answered by @bfavareto in, this is an implementation of ES6:

22.06.2018 / 21:42
6

The String.raw method is an implementation of 6th edition of ECMAScript ( ECMA-262 ) and serves to convert string templates in plain text.

According to the mentioned documentation, it converts a string into a non-interpreted literal string, meaning everything inside the string will be considered pure text, ignoring passages that can be interpreted (tags, escapes, etc.), while maintaining formatting of the string exactly as you wrote it in the code (breaking lines, spaces, tabs etc).

Example:

const template = String.raw'Primeira linha
Segunda linha
Tags <b>são ingnoradas</b>
ou qualquer tipo de interpretação,
como este escape -> \n
  <- inclusive este espaço TAB à esquerda
ou este espaço enorme ->        <-
';
console.log(template);
    
23.06.2018 / 00:36
4

The String.raw method is used to get the string clean without escaping the characters. For example:

console.log("String com caracteres \nespeciais");
console.log(String.raw'String com caracteres especiais\n');

Output:

String com caracteres
especiais
String com caracteres especiais\n

It can be useful in string templates when you want to put a regex expression inside it without escaping the "\" character.

    
22.06.2018 / 22:22