String

  • Enlace amigable (slug) de la revisión: Referencia_de_JavaScript_1.5/Objetos_globales/String
  • Título de la revisión: String
  • Id de la revisión: 142077
  • Creada:
  • Creador: Talisker
  • ¿Es la revisión actual? No
  • Comentario /* Comparing strings */

Contenido de la revisión

Resumen

Objeto del Núcle

Un objeto que representa una serie de caracteres dentro de una cadena.

Creado Por

El constructor String:

new String(cadena)

Parámetros

cadena 
Cualquier cadena.

Description

String objects are created by calling the constructor new String():

s_obj = new String("foo"); // creates a String object

The String object wraps Javascript's string primitive data type with the methods described below. The global function String() can also be called without new in front to create a primitive string:

s_prim = String("bar"); //creates a primitive string

Literal strings in Javascript source code create primitive strings:

s_also_prim = "foo"; // creates a primitive string

Because Javascript automatically converts between string primitives and String objects, you can call any of the methods of the String object on a string primitive. JavaScript automatically converts the string primitive to a temporary String object, calls the method, then discards the temporary String object. For example, you can use the String.length property on a string primitive created from a string literal:

s_obj.length;       // 3
s_prim.length;      // 3
s_also_prim.length; // 3
'foo'.length;       // 3
"foo".length;       // 3

(A string literal can use single or double quotation marks.)

String objects can be converted to primitive strings with String.valueOf().

String primitives and String objects give different results when evaluated as Javascript. Primitives are treated as source code; String objects are treated as a character sequence object. For example:

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

You can convert the value of any object into a string using the global String function.

Accessing individual characters in a string

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

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

The other way is to treat the string as an array, where each index corresponds to an individual character:

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

Note: The second way (treating the string as an array) is not part of the ECMAScript; it's a JavaScript feature.

In both cases, attempting to set an individual character won't work. Trying to set a character through charAt results in an error:

var x = 'cat';
x.charAt(0) = 'b'; // error

Setting a character via indexing does not throw an error, but the string itself is unchanged:

var x = 'cat';
x[2] = 'p';
alert(x);    // still outputs 'cat'
alert(x[2]); // still outputs 't'

Comparación de cadenas

Los programadores de C tienen la función 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
    document.write(a + " is less than " + b);
else if (a > b)
    document.write(a + " is greater than " + b);
else
    document.write(a + " and " + b + " are equal.");

Propiedades

  • constructor: Especifica la función que crea un prototipo de objeto.
  • length: Refleja la longitud de la cadena.
  • prototype: Permite la adición de propiedades a un objeto Cadena.

Métodos estáticos

  • fromCharCode: Devuelve una cadena creada por una secuencia específica de valores Unicode.

Methods

Methods unrelated to HTML

  • charAt: Returns the character at the specified index.
  • charCodeAt: Returns a number indicating the Unicode value of the character at the given index.
  • concat: Combines the text of two strings and returns a new string.
  • indexOf: Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.
  • lastIndexOf: Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.
  • match: Used to match a regular expression against a string.
  • replace: Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.
  • search: Executes the search for a match between a regular expression and a specified string.
  • slice: Extracts a section of a string and returns a new string.
  • split: Splits a String object into an array of strings by separating the string into substrings.
  • substr: Returns the characters in a string beginning at the specified location through the specified number of characters.
  • substring: Returns the characters in a string between two indexes into the string.
  • toLowerCase: Returns the calling string value converted to lowercase.
  • toSource: Returns an object literal representing the specified object; you can use this value to create a new object. Overrides the Object.toSource method.
  • toString: Returns a string representing the specified object. Overrides the Object.toString method.
  • toUpperCase: Returns the calling string value converted to uppercase.
  • valueOf: Returns the primitive value of the specified object. Overrides the Object.valueOf method.

HTML wrapper methods

{{template.No_estandar_texto()}}

Each of the following methods returns a copy of the string wrapped inside an HTML tag. For example, "test".bold() returns "<b>test</b>".

These methods are of limited use, as they provide only a subset of the available HTML tags and attributes.

Examples

Example: String primitive

The following statement creates a string primitive from the string literal "Schaefer", and assigns it to the variable last_name:

var last_name = "Schaefer";

Example: String primitive properties

The following expressions evaluate to 8, "SCHAEFER", and "schaefer", respectively:

last_name.length
last_name.toUpperCase()
last_name.toLowerCase()

Example: Setting an individual character in a string

An individual character cannot be directly set in a string. Instead, a new string can be created using the substr or substring methods:

function setCharAt(str, index, ch) {
   return str.substr(0, index) + ch + str.substr(index + 1);
}

alert(setCharAt('scam', 1, 'p')); // outputs "spam"

Example: Pass a string among scripts in different windows or frames

The following code creates two string variables and opens a second window:

var lastName = "Schaefer";
var firstName = "Jesse";
empWindow = window.open('string2.html', 'window1', 'width=300,height=300');

If the HTML source for the second window (string2.html) creates two string variables, empLastName and empFirstName, the following code in the first window assigns values to the second window's variables:

empWindow.empFirstName = firstName;
empWindow.empLastName = lastName;

The following code in the first window displays the values of the second window's variables:

alert('empFirstName in empWindow is ' + empWindow.empFirstName);
alert('empLastName in empWindow is ' + empWindow.empLastName);


{{ wiki.languages( { "en": "en/Core_JavaScript_1.5_Reference/Global_Objects/String", "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Objets_globaux/String", "ja": "ja/Core_JavaScript_1.5_Reference/Global_Objects/String", "pl": "pl/Dokumentacja_j\u0119zyka_JavaScript_1.5/Obiekty/String" } ) }}

Fuente de la revisión

<p>
</p>
<h3 name="Resumen"> Resumen </h3>
<p><b>Objeto del Núcle</b>
</p><p>Un objeto que representa una serie de caracteres dentro de una cadena.
</p>
<h3 name="Creado_Por"> Creado Por </h3>
<p>El constructor String:
</p>
<pre class="eval">new String(<i>cadena</i>)
</pre>
<h3 name="Par.C3.A1metros"> Parámetros </h3>
<dl><dt> <code>cadena</code> </dt><dd> Cualquier cadena.
</dd></dl>
<h3 name="Description"> Description </h3>
<p>String objects are created by calling the constructor <code>new String()</code>:
</p>
<pre class="eval">s_obj = new String("foo"); // creates a String object
</pre>
<p>The <code>String</code> object wraps Javascript's string primitive data type with the methods described below. The global function <code>String()</code> can also be called without <code>new</code> in front to create a primitive string:
</p>
<pre class="eval">s_prim = String("bar"); //creates a primitive string
</pre>
<p>Literal strings in Javascript source code create primitive strings:
</p>
<pre class="eval">s_also_prim = "foo"; // creates a primitive string
</pre>
<p>Because Javascript automatically converts between string primitives and String objects, you can call any of the methods of the <code>String</code> object on a string primitive. JavaScript automatically converts the string primitive to a temporary <code>String</code> object, calls the method, then discards the temporary <code>String</code> object. For example, you can use the <code>String.length</code> property on a string primitive created from a string literal:
</p>
<pre class="eval">s_obj.length;       // 3
s_prim.length;      // 3
s_also_prim.length; // 3
'foo'.length;       // 3
"foo".length;       // 3
</pre>
<p>(A string literal can use single or double quotation marks.) 
</p><p>String objects can be converted to primitive strings with <code>String.valueOf()</code>.
</p><p>String primitives and String objects give different results when evaluated as Javascript. Primitives are treated as source code; String objects are treated as a character sequence object. For example:
</p>
<pre class="eval">s1 = "2 + 2" // creates a string primitive
s2 = new String("2 + 2") // creates a String object
eval(s1)     // returns the number 4
eval(s2)     // returns the string "2 + 2"
eval(s2.valueOf()); // returns the number 4
</pre>
<p>You can convert the value of any object into a string using the global <a href="es/Referencia_de_JavaScript_1.5/Funciones/String">String</a> function.
</p>
<h4 name="Accessing_individual_characters_in_a_string"> Accessing individual characters in a string </h4>
<p>There are two ways to access an individual character in a string. The first is the <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/charAt">charAt</a> method:
</p>
<pre class="eval">'cat'.charAt(1) // returns "a"
</pre>
<p>The other way is to treat the string as an array, where each index corresponds to an individual character:
</p>
<pre class="eval">'cat'[1] // returns "a"
</pre>
<p>Note: The second way (treating the string as an array) is not part of the ECMAScript; it's a JavaScript feature.
</p><p>In both cases, attempting to set an individual character won't work. Trying to set a character through <code>charAt</code> results in an error:
</p>
<pre class="eval">var x = 'cat';
x.charAt(0) = 'b'; // error
</pre>
<p>Setting a character via indexing does not throw an error, but the string itself is unchanged:
</p>
<pre class="eval">var x = 'cat';
x[2] = 'p';
alert(x);    // still outputs 'cat'
alert(x[2]); // still outputs 't'
</pre>
<h4 name="Comparaci.C3.B3n_de_cadenas"> Comparación de cadenas </h4>
<p>Los programadores de C tienen la función <code>strcmp()</code> function for comparing strings. In JavaScript, you just use the less-than and greater-than operators:
</p>
<pre class="eval">var a = "a";
var b = "b";
if (a &lt; b) // true
    document.write(a + " is less than " + b);
else if (a &gt; b)
    document.write(a + " is greater than " + b);
else
    document.write(a + " and " + b + " are equal.");
</pre>
<h3 name="Propiedades"> Propiedades </h3>
<ul><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/constructor">constructor</a>: Especifica la función que crea un prototipo de objeto.  
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/length">length</a>: Refleja la longitud de la cadena.  
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/prototype">prototype</a>: Permite la adición de propiedades a un objeto Cadena.
</li></ul>
<h3 name="M.C3.A9todos_est.C3.A1ticos"> Métodos estáticos </h3>
<ul><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/fromCharCode">fromCharCode</a>: Devuelve una cadena creada por una secuencia específica de valores Unicode.
</li></ul>
<h3 name="Methods"> Methods </h3>
<h4 name="Methods_unrelated_to_HTML"> Methods unrelated to HTML </h4>
<ul><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/charAt">charAt</a>: Returns the character at the specified index.
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/charCodeAt">charCodeAt</a>: Returns a number indicating the Unicode value of the character at the given index.
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/concat">concat</a>: Combines the text of two strings and returns a new string.
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/indexOf">indexOf</a>: Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/lastIndexOf">lastIndexOf</a>: Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/match">match</a>: Used to match a regular expression against a string.
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/replace">replace</a>: Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/search">search</a>: Executes the search for a match between a regular expression and a specified string.
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/slice">slice</a>: Extracts a section of a string and returns a new string.
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/split">split</a>: Splits a String object into an array of strings by separating the string into substrings.
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/substr">substr</a>: Returns the characters in a string beginning at the specified location through the specified number of characters.
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/substring">substring</a>: Returns the characters in a string between two indexes into the string.
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/toLowerCase">toLowerCase</a>: Returns the calling string value converted to lowercase.
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/toSource">toSource</a>: Returns an object literal representing the specified object; you can use this value to create a new object. Overrides the <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/Object/toSource">Object.toSource</a> method.
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/toString">toString</a>: Returns a string representing the specified object. Overrides the <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/Object/toString">Object.toString</a> method.
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/toUpperCase">toUpperCase</a>: Returns the calling string value converted to uppercase.
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/valueOf">valueOf</a>: Returns the primitive value of the specified object. Overrides the <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/Object/valueOf">Object.valueOf</a> method.
</li></ul>
<h4 name="HTML_wrapper_methods"> HTML wrapper methods </h4>
<p>{{template.No_estandar_texto()}}
</p><p>Each of the following methods returns a copy of the string wrapped inside an HTML tag. For example, "test".bold() returns "&lt;b&gt;test&lt;/b&gt;".
</p>
<ul><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/anchor">anchor</a>: <a class="external" href="http://www.w3.org/TR/html401/struct/links.html#adef-name-A"><code>&lt;a name="<i>name</i>"&gt;</code></a> (hypertext target)
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/big">big</a>: <a class="external" href="http://www.w3.org/TR/html401/present/graphics.html#edef-BIG"><code>&lt;big&gt;</code></a>
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/blink">blink</a>: <code>&lt;blink&gt;</code>
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/bold">bold</a>: <a class="external" href="http://www.w3.org/TR/html401/present/graphics.html#edef-B"><code>&lt;b&gt;</code></a>
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/fixed">fixed</a>: <a class="external" href="http://www.w3.org/TR/html401/present/graphics.html#edef-TT"><code>&lt;tt&gt;</code></a>
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/fontcolor">fontcolor</a>: <code>&lt;font color="<i>color</i>"&gt;</code>
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/fontsize">fontsize</a>: <code>&lt;font size="<i>size</i>"&gt;</code>
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/italics">italics</a>: <a class="external" href="http://www.w3.org/TR/html401/present/graphics.html#edef-I"><code>&lt;i&gt;</code></a>
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/link">link</a>: <a class="external" href="http://www.w3.org/TR/html401/struct/links.html#adef-href"><code>&lt;a href="<i>url</i>"&gt;</code></a> (link to URL)
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/small">small</a>: <a class="external" href="http://www.w3.org/TR/html401/present/graphics.html#edef-SMALL"><code>&lt;small&gt;</code></a>.
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/strike">strike</a>: <a class="external" href="http://www.w3.org/TR/html401/present/graphics.html#edef-STRIKE"><code>&lt;strike&gt;</code></a>
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/sub">sub</a>: <a class="external" href="http://www.w3.org/TR/html401/struct/text.html#edef-SUB"><code>&lt;sub&gt;</code></a>
</li><li> <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/sup">sup</a>: <a class="external" href="http://www.w3.org/TR/html401/struct/text.html#edef-SUP"><code>&lt;sup&gt;</code></a>
</li></ul>
<p>These methods are of limited use, as they provide only a subset of the available HTML tags and attributes.
</p>
<h3 name="Examples"> Examples </h3>
<h4 name="Example:_String_primitive"> Example: String primitive </h4>
<p>The following statement creates a string primitive from the string literal "Schaefer", and assigns it to the variable <code>last_name</code>:
</p>
<pre class="eval">var last_name = "Schaefer";
</pre>
<h4 name="Example:_String_primitive_properties"> Example: String primitive properties </h4>
<p>The following expressions evaluate to <code>8</code>, "<code>SCHAEFER</code>", and "<code>schaefer</code>", respectively:
</p>
<pre class="eval">last_name.length
last_name.toUpperCase()
last_name.toLowerCase()
</pre>
<h4 name="Example:_Setting_an_individual_character_in_a_string"> Example: Setting an individual character in a string </h4>
<p>An individual character cannot be directly set in a string. Instead, a new string can be created using the <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/substr">substr</a> or <a href="es/Referencia_de_JavaScript_1.5/Objetos_globales/String/substring">substring</a> methods:
</p>
<pre class="eval">function setCharAt(str, index, ch) {
   return str.substr(0, index) + ch + str.substr(index + 1);
}

alert(setCharAt('scam', 1, 'p')); // outputs "spam"
</pre>
<h4 name="Example:_Pass_a_string_among_scripts_in_different_windows_or_frames"> Example: Pass a string among scripts in different windows or frames </h4>
<p>The following code creates two string variables and opens a second window:
</p>
<pre class="eval">var lastName = "Schaefer";
var firstName = "Jesse";
empWindow = window.open('string2.html', 'window1', 'width=300,height=300');
</pre>
<p>If the HTML source for the second window (<code>string2.html</code>) creates two string variables, <code>empLastName</code> and <code>empFirstName</code>, the following code in the first window assigns values to the second window's variables:
</p>
<pre class="eval">empWindow.empFirstName = firstName;
empWindow.empLastName = lastName;
</pre>
<p>The following code in the first window displays the values of the second window's variables:
</p>
<pre class="eval">alert('empFirstName in empWindow is ' + empWindow.empFirstName);
alert('empLastName in empWindow is ' + empWindow.empLastName);
</pre>
<p><br>
</p>
<div class="noinclude">
</div>
{{ wiki.languages( { "en": "en/Core_JavaScript_1.5_Reference/Global_Objects/String", "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Objets_globaux/String", "ja": "ja/Core_JavaScript_1.5_Reference/Global_Objects/String", "pl": "pl/Dokumentacja_j\u0119zyka_JavaScript_1.5/Obiekty/String" } ) }}
Revertir a esta revisión