diff options
Diffstat (limited to 'files/pt-pt/web/javascript/reference/global_objects/string/index.html')
-rw-r--r-- | files/pt-pt/web/javascript/reference/global_objects/string/index.html | 326 |
1 files changed, 326 insertions, 0 deletions
diff --git a/files/pt-pt/web/javascript/reference/global_objects/string/index.html b/files/pt-pt/web/javascript/reference/global_objects/string/index.html new file mode 100644 index 0000000000..4ccc8f5f81 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/string/index.html @@ -0,0 +1,326 @@ +--- +title: String +slug: Web/JavaScript/Reference/Global_Objects/String +tags: + - ECMAScript 2015 + - JavaScript + - Referencia + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +<div>{{JSRef}}</div> + +<p>O objeto global <strong><code>String</code></strong> é um construtor de <em>strings</em> ou sequência de carateres.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<p>Os literais de string assumem as formas:</p> + +<pre class="syntaxbox"><code>'string text' +"string text" +"中文 español English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ்"</code></pre> + +<p>As Strings podem também ser criadas usando o objecto global string directamente:</p> + +<pre class="syntaxbox"><code>String(thing) +new String(thing)</code></pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>thing</code></dt> + <dd>Qualquer parâmetro para ser convertido numa <em>string</em>.</dd> +</dl> + +<h3 id="Strings_modelo"><em>Strings </em>modelo</h3> + +<p>A partir de ECMAScript 2015, os literais de <em>strings</em> podem também ser chamados de <a href="/en-US/docs/Web/JavaScript/Reference/template_strings">Modelo strings</a>:</p> + +<pre class="brush: js"><code>`hello world`</code> +`hello! + world!` +<code>`hello ${who}`</code> +<code>escape `<a>${who}</a>`</code></pre> + +<dl> +</dl> + +<h3 id="Notação_Escape">Notação <em>Escape</em></h3> + +<p>Além dos carateres regulares e imprmiveis, os carateres especiais também podem ser codificados com notação <em>escape</em>:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Código</th> + <th scope="col">Resultado</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>\XXX</code> (<code>XXX</code> = 1 - 3 octal digits; range of 0 - 377)</td> + <td>ISO-8859-1 character / Unicode code point between U+0000 and U+00FF</td> + </tr> + <tr> + <td><code>\'</code></td> + <td>Aspas simples</td> + </tr> + <tr> + <td><code>\"</code></td> + <td>Aspas duplas</td> + </tr> + <tr> + <td><code>\\</code></td> + <td>Barra invertida</td> + </tr> + <tr> + <td><code>\n</code></td> + <td>Nova linha</td> + </tr> + <tr> + <td><code>\r</code></td> + <td>carriage return</td> + </tr> + <tr> + <td><code>\v</code></td> + <td>Tab vertical</td> + </tr> + <tr> + <td><code>\t</code></td> + <td>Tab</td> + </tr> + <tr> + <td><code>\b</code></td> + <td>backspace</td> + </tr> + <tr> + <td><code>\f</code></td> + <td>form feed</td> + </tr> + <tr> + <td><code>\uXXXX</code> (<code>XXXX</code> = 4 hex digits; range of 0x0000 - 0xFFFF)</td> + <td>UTF-16 code unit / Unicode code point between U+0000 and U+FFFF</td> + </tr> + <tr> + <td><code>\u{X}</code> ... <code>\u{XXXXXX}</code> (<code>X…XXXXXX</code> = 1 - 6 hex digits; range of 0x0 - 0x10FFFF)</td> + <td>UTF-32 code unit / Unicode code point between U+0000 and U+10FFFF {{experimental_inline}}</td> + </tr> + <tr> + <td><code>\xXX</code> (<code>XX</code> = 2 hex digits; range of 0x00 - 0xFF)</td> + <td>ISO-8859-1 character / Unicode code point between U+0000 and U+00FF</td> + </tr> + </tbody> +</table> + +<div class="note"> +<p><strong>Note: </strong>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.</p> +</div> + +<h3 id="Strings_literais_longas"><em>Strings </em>literais longas</h3> + +<p>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.</p> + +<p>You can use the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Addition_()">+</a> operator to append multiple strings together, like this:</p> + +<pre class="brush: js">let longString = "This is a very long string which needs " + + "to wrap across multiple lines because " + + "otherwise my code is unreadable."; +</pre> + +<p>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:</p> + +<pre class="brush: js">let longString = "This is a very long string which needs \ +to wrap across multiple lines because \ +otherwise my code is unreadable."; +</pre> + +<p>Both of these result in identical strings being created.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>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 {{jsxref("String.length", "length")}}, to build and concatenate them using the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/String_Operators">+ and += string operators</a>, checking for the existence or location of substrings with the {{jsxref("String.prototype.indexOf()", "indexOf()")}} method, or extracting substrings with the {{jsxref("String.prototype.substring()", "substring()")}} method.</p> + +<h3 id="Acesso_de_caráter">Acesso de caráter</h3> + +<p>There are two ways to access an individual character in a string. The first is the {{jsxref("String.prototype.charAt()", "charAt()")}} method:</p> + +<pre class="brush: js">return 'cat'.charAt(1); // returns "a" +</pre> + +<p>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:</p> + +<pre class="brush: js">return 'cat'[1]; // returns "a" +</pre> + +<p>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 {{jsxref("Object.defineProperty()")}} for more information.)</p> + +<h3 id="Comparação_de_strings">Comparação de <em>strings</em></h3> + +<p>C developers have the <code>strcmp()</code> function for comparing strings. In JavaScript, you just use the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">less-than and greater-than operators</a>:</p> + +<pre class="brush: js">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.'); +} +</pre> + +<p>A similar result can be achieved using the {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} method inherited by <code>String</code> instances.</p> + +<h3 id="Distinção_entre_string_primitivas_e_objetos_String">Distinção entre <em>string</em> primitivas e objetos <em><code>String</code></em></h3> + +<p>Note that JavaScript distinguishes between <code>String</code> objects and primitive string values. (The same is true of {{jsxref("Boolean")}} and {{jsxref("Global_Objects/Number", "Numbers")}}.)</p> + +<p>String literals (denoted by double or single quotes) and strings returned from <code>String</code> calls in a non-constructor context (i.e., without using the {{jsxref("Operators/new", "new")}} keyword) are primitive strings. JavaScript automatically converts primitives to <code>String</code> objects, so that it's possible to use <code>String</code> 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.</p> + +<pre class="brush: js">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.'); +} +</pre> + +<p>A similar result can be achieved using the {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} method inherited by <code>String</code> instances.</p> + +<div class="blockIndicator note"> +<p>Nota: <code>a == b</code> 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:</p> + +<p><code>function isEqual(str1, str2)<br> + {<br> + return str1.toUpperCase()===str2.toUpperCase();<br> + } // isEqual</code></p> + +<p>Upper case is used instead of lower case in this function due to problems with certain UTF-8 character conversions.</p> +</div> + +<h3 id="Distinção_entre_string_primitivas_e_objetos_String_2">Distinção entre <em>string</em> primitivas e objetos <em><code>String</code></em></h3> + +<p>Note that JavaScript distinguishes between <code>String</code> objects and primitive string values. (The same is true of {{jsxref("Boolean")}} and {{jsxref("Global_Objects/Number", "Numbers")}}.)</p> + +<p>String literals (denoted by double or single quotes) and strings returned from <code>String</code> calls in a non-constructor context (i.e., without using the {{jsxref("Operators/new", "new")}} keyword) are primitive strings. JavaScript automatically converts primitives to <code>String</code> objects, so that it's possible to use <code>String</code> 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.</p> + +<pre class="brush: js">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" +</pre> + +<p>String primitives and <code>String</code> objects also give different results when using {{jsxref("Global_Objects/eval", "eval()")}}. Primitives passed to <code>eval</code> are treated as source code; <code>String</code> objects are treated as all other objects are, by returning the object. For example:</p> + +<pre class="brush: js">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" +</pre> + +<p>For these reasons, the code may break when it encounters <code>String</code> objects when it expects a primitive string instead, although generally, authors need not worry about the distinction.</p> + +<p>A <code>String</code> object can always be converted to its primitive counterpart with the {{jsxref("String.prototype.valueOf()", "valueOf()")}} method.</p> + +<pre class="brush: js">console.log(eval(s2.valueOf())); // returns the number 4 +</pre> + +<div class="note"><strong>Nota:</strong> For another possible approach to strings in JavaScript, please read the article about <a href="/en-US/Add-ons/Code_snippets/StringView"><code>StringView</code> — a C-like representation of strings based on typed arrays</a>.</div> + +<h2 id="Propriedades">Propriedades</h2> + +<dl> + <dt>{{jsxref("String.prototype")}}</dt> + <dd>Allows the addition of properties to a <code>String</code> object.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{jsxref("String.fromCharCode()")}}</dt> + <dd>Returns a string created by using the specified sequence of Unicode values.</dd> + <dt>{{jsxref("String.fromCodePoint()")}}</dt> + <dd>Returns a string created by using the specified sequence of code points.</dd> + <dt>{{jsxref("String.raw()")}} {{experimental_inline}}</dt> + <dd>Returns a string created from a raw template string.</dd> +</dl> + +<h2 id="Instâncias_de_String">Instâncias de <em><code>String</code></em></h2> + +<h3 id="Propriedades_2">Propriedades</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properties')}}</div> + +<h3 id="Métodos_2">Métodos</h3> + +<h4 id="Methods_unrelated_to_HTML">Methods unrelated to HTML</h4> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods_unrelated_to_HTML')}}</div> + +<h4 id="HTML_wrapper_methods">HTML wrapper methods</h4> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'HTML_wrapper_methods')}}</div> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Conversão_de_String">Conversão de <em>String</em></h3> + +<p>It's possible to use <code>String</code> as a more reliable {{jsxref("String.prototype.toString()", "toString()")}} alternative, as it works when used on {{jsxref("null")}}, {{jsxref("undefined")}}, and on {{jsxref("Symbol", "symbols")}}. For example:</p> + +<pre class="brush: js">var outputStrings = []; +for (var i = 0, n = inputValues.length; i < n; ++i) { + outputStrings.push(String(inputValues[i])); +} +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-string-objects', 'String')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-string-objects', 'String')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5', 'String')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("javascript.builtins.String",2)}}</p> + +<h2 id="Consulte_também">Consulte também:</h2> + +<ul> + <li>{{domxref("DOMString")}}</li> + <li><a href="/en-US/Add-ons/Code_snippets/StringView"><code>StringView</code> — a C-like representation of strings based on typed arrays</a></li> + <li><a href="/en-US/docs/Web/API/DOMString/Binary">Binary strings</a></li> +</ul> |