String

O objeto global String é um construtor de strings ou sequência de carateres.

Sintaxe

Os literais de string assumem as formas:

'string text'
"string text"
"中文 español English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ்"

As Strings podem também ser criadas usando o objecto global string directamente:

String(thing)
new String(thing)

Parâmetros

thing
Qualquer parâmetro para ser convertido numa string.

Strings modelo

A partir de ECMAScript 2015, os literais de strings podem também ser chamados de Modelo strings:

`hello world`
`hello!
 world!`
`hello ${who}`
escape `<a>${who}</a>`

Notação Escape

Além dos carateres regulares e imprmiveis, os carateres especiais também podem ser codificados com notação escape:

Código Resultado
\XXX (XXX = 1 - 3 octal digits; range of 0 - 377) ISO-8859-1 character / Unicode code point between U+0000 and U+00FF
\' Aspas simples
\" Aspas duplas
\\ Barra invertida
\n Nova linha
\r carriage return
\v Tab vertical
\t Tab
\b backspace
\f form feed
\uXXXX (XXXX = 4 hex digits; range of 0x0000 - 0xFFFF) UTF-16 code unit / Unicode code point between U+0000 and U+FFFF
\u{X} ... \u{XXXXXX} (X…XXXXXX = 1 - 6 hex digits; range of 0x0 - 0x10FFFF) UTF-32 code unit / Unicode code point between U+0000 and U+10FFFF This is an experimental API that should not be used in production code.
\xXX (XX = 2 hex digits; range of 0x00 - 0xFF) ISO-8859-1 character / Unicode code point between U+0000 and U+00FF

Note: Ao contrário de algumas outras linguagens, o Javascript não faz distinção entre strings com aspas simples e aspas duplas; Portanto a notação "escape" funciona em strings independente se foi utilizada aspas simples, ou aspas duplas na criação.

Strings literais longas

Sometimes, your code will include strings which are very long. Rather than having lines that go on endlessly, or wrap at the whim of your editor, you may wish to specifically break the string into multiple lines in the source code without affecting the actual string contents. There are two ways you can do this.

You can use the + operator to append multiple strings together, like this:

let longString = "This is a very long string which needs " +
                 "to wrap across multiple lines because " +
                 "otherwise my code is unreadable.";

Or you can use the backslash character ("\") at the end of each line to indicate that the string will continue on the next line. Make sure there is no space or any other character after the backslash (except for a line break), or as an indent; otherwise it will not work. That form looks like this:

let longString = "This is a very long string which needs \
to wrap across multiple lines because \
otherwise my code is unreadable.";

Both of these result in identical strings being created.

Descrição

Strings are useful for holding data that can be represented in text form. Some of the most-used operations on strings are to check their length, to build and concatenate them using the + and += string operators, checking for the existence or location of substrings with the indexOf() method, or extracting substrings with the substring() (en-US) method.

Acesso de caráter

There are two ways to access an individual character in a string. The first is the charAt() (en-US) method:

return 'cat'.charAt(1); // returns "a"

The other way (introduced in ECMAScript 5) is to treat the string as an array-like object, where individual characters correspond to a numerical index:

return 'cat'[1]; // returns "a"

For character access using bracket notation, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable. (See Object.defineProperty() (en-US) for more information.)

Comparação de strings

C developers have the strcmp() function for comparing strings. In JavaScript, you just use the less-than and greater-than operators:

var a = 'a';
var b = 'b';
if (a < b) { // true
  console.log(a + ' is less than ' + b);
} else if (a > b) {
  console.log(a + ' is greater than ' + b);
} else {
  console.log(a + ' and ' + b + ' are equal.');
}

A similar result can be achieved using the localeCompare() (en-US) method inherited by String instances.

Distinção entre string primitivas e objetos String

Note that JavaScript distinguishes between String objects and primitive string values. (The same is true of Boolean and Numbers.)

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the new (en-US) keyword) are primitive strings. JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

var a = 'a';
var b = 'b';
if (a < b) { // true
  console.log(a + ' is less than ' + b);
} else if (a > b) {
  console.log(a + ' is greater than ' + b);
} else {
  console.log(a + ' and ' + b + ' are equal.');
}

A similar result can be achieved using the localeCompare() (en-US) method inherited by String instances.

Nota: a == b compares the strings in a and b for being equal in the usual case-sensitive way. If you wish to compare without regard to upper or lower case characters, use a function similar to this:

function isEqual(str1, str2)
    {
    return str1.toUpperCase()===str2.toUpperCase();
    } // isEqual

Upper case is used instead of lower case in this function due to problems with certain UTF-8 character conversions.

Distinção entre string primitivas e objetos String

Note that JavaScript distinguishes between String objects and primitive string values. (The same is true of Boolean and Numbers.)

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the new (en-US) keyword) are primitive strings. JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

var s_prim = 'foo';
var s_obj = new String(s_prim);

console.log(typeof s_prim); // Logs "string"
console.log(typeof s_obj);  // Logs "object"

String primitives and String objects also give different results when using eval() (en-US). Primitives passed to eval are treated as source code; String objects are treated as all other objects are, by returning the object. For example:

var s1 = '2 + 2';             // creates a string primitive
var s2 = new String('2 + 2'); // creates a String object
console.log(eval(s1));        // returns the number 4
console.log(eval(s2));        // returns the string "2 + 2"

For these reasons, the code may break when it encounters String objects when it expects a primitive string instead, although generally, authors need not worry about the distinction.

A String object can always be converted to its primitive counterpart with the valueOf() (en-US) method.

console.log(eval(s2.valueOf())); // returns the number 4
Nota: For another possible approach to strings in JavaScript, please read the article about StringView — a C-like representation of strings based on typed arrays.

Propriedades

String.prototype (en-US)
Allows the addition of properties to a String object.

Métodos

String.fromCharCode() (en-US)
Returns a string created by using the specified sequence of Unicode values.
String.fromCodePoint() (en-US)
Returns a string created by using the specified sequence of code points.
String.raw() (en-US) This is an experimental API that should not be used in production code.
Returns a string created from a raw template string.

Instâncias de String

Propriedades

{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properties')}}

Métodos

Methods unrelated to HTML

{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods_unrelated_to_HTML')}}

HTML wrapper methods

Exemplos

Conversão de String

It's possible to use String as a more reliable toString() (en-US) alternative, as it works when used on null, undefined, and on symbols. For example:

var outputStrings = [];
for (var i = 0, n = inputValues.length; i < n; ++i) {
  outputStrings.push(String(inputValues[i]));
}

Especificações

Especificação Estado Comentário
ECMAScript (ECMA-262)
The definition of 'String' in that specification.
Living Standard
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'String' in that specification.
Standard
ECMAScript 5.1 (ECMA-262)
The definition of 'String' in that specification.
Standard
ECMAScript 1st Edition (ECMA-262) Standard Initial definition.

Compatibilidade de navegador

BCD tables only load in the browser

Consulte também: