You are on page 1of 10

JavaScript String prototype substring()

String.prototype.substring()
Resumen

El substring() método devuelve un subconjunto de un objeto String.

Sintaxis
cadena.substring(indiceA[, indiceB'])
Parámetros
indiceA

Un entero entre 0 y la longitud de la cadena menos 1.


indiceB

(opcional) Un entero entre 0 y la longitud de la cadena.

Descripción

substring extrae caracteres desde indiceA hasta indiceB sin incluirlo. En particular:

 Si indiceA es igual a indiceB, substring devuelve una cadena vacía.


 Si se omite el indiceB, substring extrae caracteres hasta el final de la cadena.
 Si el argumento es menor que 0 o es NaN, se trata como si fuese 0.
 Si el argumento es mayor que nombreCadena.length, se trata como si fuese
nombreCadena.length.

Si indiceA es mayor que indiceB, entonces el efecto de substring es como si los dos
argumentos se intercambiasen; por ejemplo, cadena.substring(1, 0) ==
cadena.substring(0, 1).

Ejemplos
Ejemplo: Usando substring

El siguiente ejemplo usa substring para mostrar caracteres de la cadena "Mozilla":

// asume una función print ya definida


var cualquierCadena = "Mozilla";

// Muestra "Moz"
print(cualquierCadena.substring(0,3));
print(cualquierCadena.substring(3,0));

// Muestra "lla"
print(cualquierCadena.substring(4,7));
print(cualquierCadena.substring(7,4));

// Muestra "Mozill"
print(cualquierCadena.substring(0,6));

// Muestra "Mozilla"
print(cualquierCadena.substring(0,7));
print(cualquierCadena.substring(0,10));
Ejemplo: Reemplazar una subcadena dentro de una cadena

El siguiente ejemplo reemplaza una subcadena dentro de una cadena. Reemplazará tanto
caracteres individuales como subcadenas. La llamada de la función al final del ejemplo
cambia la cadena "Bravo Nuevo Mundo" por "Bravo Nueva Web".

function reemplazarCadena(cadenaVieja, cadenaNueva, cadenaCompleta) {


// Reemplaza cadenaVieja por cadenaNueva en cadenaCompleta

for (var i = 0; i < cadenaCompleta.length; i++) {


if (cadenaCompleta.substring(i, i + cadenaVieja.length) ==
cadenaVieja) {
cadenaCompleta= cadenaCompleta.substring(0, i) + cadenaNueva +
cadenaCompleta.substring(i + cadenaVieja.length, cadenaCompleta.length);
}
}
return cadenaCompleta;
}

reemplazarCadena("Mundo", "Web", "Bravo Nuevo Mundo");


Vea También

 String.prototype.substr()
 String.prototype.slice()
String.prototype.substr()
Resumen

El substr() método devuelve los caracteres de una cadena comenzando en la localización


especificada, y en el número de caracteres especificado.

Sintaxis
cadena.substr(start[, length])
Parámetros
inicio

Localización en la cual se empieza a extraer caracteres (un entero entre 0 y la longitud de


la cadena menos 1).
longitud

El número de caracteres a extraer.

Descripción

inicio es un índice de un carácter. El índice del primer carácter es 0, y el índice del último
carácter es la longitud de la cadena menos 1. substr comienza extrayendo caracteres a
partir del inicio y recoge longitud de caracteres (a menos que se alcance el final de la
primera cadena, en cuyo caso se devuelven menos).

Si inicio es positivo y es mayor o igual que la longitud de la cadena, substr devuelve una
cadena vacía.

Si inicio es negativo, substr lo usa como un índice del carácter desde el final de la
cadena. Si inicio es negativo y abs(inicio) es mayor que la longitud de la cadena,
substr usa 0 como índice inical. Nota: la manipulación de valores negativos de el
argumento inicio no es soportada por Microsoft JScript .

Si longitud es 0 o negativa, substr devuelve una cadena vacía. Si se omite longitud,


inicio extrae caracteres hasta el final de la cadena.

Ejemplos
Ejemplo: Usando substr

Considera el siguiente script:

// asume una función print ya definida


var cadena = "abcdefghij";
console.log("(1,2): " + cadena.substr(1,2));
console.log("(-3,2): " + cadena.substr(-3,2));
console.log("(-3): " + cadena.substr(-3));
console.log("(1): " + cadena.substr(1));
console.log("(-20, 2): " + cadena.substr(-20,2));
console.log("(20, 2): " + cadena.substr(20,2));

Este script muestra:

(1,2): bc
(-3,2): hi
(-3): hij
(1): bcdefghij
(-20, 2): ab
(20, 2):
String.prototype.slice()
Resumen

El slice() método extrae una sección de una cadena y devuelve una cadena nueva.

Sintaxis
str.slice(beginSlice[, endSlice])
Parameters
comienzoTrozo

El índice sobre cero en el cual empieza la extracción.


finalTrozo

El índice sobre cero en el que termina la extracción. Si se omite, slice extrae hasta el
final de la cadena.

Descripción

slice extrae el texto de una cadena y devuelve una nueva cadena. Los cambios en el texto
de una cadena no afectan a la otra cadena.

slice extrae hasta, pero sin incluir finalTrozo. string.slice(1,4) extrae del segundo
carácter hasta el cuarto carácter (caracteres con índice 1, 2 y 3).

Si se usa un índice negativo, finalTrozo indica el punto desde el final de la cadena.


string.slice(2,-1) extrae desde tercer carácter hasta el último carácter de la cadena.

Ejemplos
Ejemplo: Usando slice para crear una nueva cadena

El siguiente ejemplo usa slice para crear una nueva cadena.

// asume la definición de una función print


var cadena1 = "La mañana se nos echa encima.";
var cadena2 = cadena1.slice(3, -2);
print(cadena2);

Esto escribe:

mañana se nos echa encim


Array.prototype.slice()
El medoto slice() devuelve una copia de una parte del array dentro de un nuevo array.

Sintaxis
arr.slice([inicio [, fin]])
Parametros
inicio

Indice donde empieza la extracción.

Un numero negativo indica un desplazamiento desde el final del array. slice(-2)extrae


los dos últimos elementos del array

si inicio es omitido el valor por defecto es 0.


fin

Índice que marca el fin a la extracción. slice extrae hasta, pero sin incluir el final.

slice(1,4) extrae desde el segundo elemento hasta el cuarto (los elementos de los
indices 1, 2, y 3).

As a negative index, end indicates an offset from the end of the sequence. slice(2,-1)
extracts the third element through the second-to-last element in the sequence.

If end is omitted, slice extracts to the end of the sequence (arr.length).

Descripción

slicedoes not alter. It returns a shallow copy of elements from the original array.
Elements of the original array are copied into the returned array as follows:

 For object references (and not the actual object), slice copies object references into the
new array. Both the original and new array refer to the same object. If a referenced object
changes, the changes are visible to both the new and original arrays.
 For strings and numbers (not String and Number objects), slice copies strings and
numbers into the new array. Changes to the string or number in one array does not affect
the other array.

If a new element is added to either array, the other array is not affected.

Ejemplos
Example: Return a portion of an existing array
// Our good friend the citrus from fruits example
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(1, 3);

// citrus contains ['Orange','Lemon']


Example: Using slice

In the following example, slice creates a new array, newCar, from myCar. Both include a
reference to the object myHonda. When the color of myHonda is changed to purple, both
arrays reflect the change.

// Using slice, create newCar from myCar.


var myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size:
2.2 } };
var myCar = [myHonda, 2, 'cherry condition', 'purchased 1997'];
var newCar = myCar.slice(0, 2);

// Display the values of myCar, newCar, and the color of myHonda


// referenced from both arrays.
console.log('myCar = ' + myCar.toSource());
console.log('newCar = ' + newCar.toSource());
console.log('myCar[0].color = ' + myCar[0].color);
console.log('newCar[0].color = ' + newCar[0].color);

// Change the color of myHonda.


myHonda.color = 'purple';
console.log('The new color of my Honda is ' + myHonda.color);

// Display the color of myHonda referenced from both arrays.


console.log('myCar[0].color = ' + myCar[0].color);
console.log('newCar[0].color = ' + newCar[0].color);

This script writes:

myCar = [{color:'red', wheels:4, engine:{cylinders:4, size:2.2}}, 2,


'cherry condition', 'purchased 1997']
newCar = [{color:'red', wheels:4, engine:{cylinders:4, size:2.2}}, 2]
myCar[0].color = red
newCar[0].color = red
The new color of my Honda is purple
myCar[0].color = purple
newCar[0].color = purple
Array-like objects

slice method can also be called to convert Array-like objects / collections to a new Array.
You just bind the method to the object. The arguments inside a function is an example of
an 'array-like object'.

function list() {
return Array.prototype.slice.call(arguments, 0);
}

var list1 = list(1, 2, 3); // [1, 2, 3]

Binding can be done with the .call function of Function.prototype and it can also be
reduced using [].slice.call(arguments) instead of Array.prototype.slice.call.
Anyway, it can be simplified using bind.
var unboundSlice = Array.prototype.slice;
var slice = Function.prototype.call.bind(unboundSlice);

function list() {
return slice(arguments, 0);
}

var list1 = list(1, 2, 3); // [1, 2, 3]


Streamlining cross-browser behavior

Although host objects (such as DOM objects) are not required by spec to follow the
Mozilla behavior when converted by Array.prototype.slice and IE < 9 does not do so,
versions of IE starting with version 9 do allow this, “shimming” it can allow reliable cross-
browser behavior. As long as other modern browsers continue to support this ability, as
currently do IE, Mozilla, Chrome, Safari, and Opera, developers reading (DOM-
supporting) slice code relying on this shim will not be misled by the semantics; they can
safely rely on the semantics to provide the now apparently de facto standard behavior. (The
shim also fixes IE to work with the second argument of slice() being an explicit
null/undefined value as earlier versions of IE also did not allow but all modern browsers,
including IE >= 9, now do.)

/**
* Shim for "fixing" IE's lack of support (IE < 9) for applying slice
* on host objects like NamedNodeMap, NodeList, and HTMLCollection
* (technically, since host objects have been implementation-dependent,
* at least before ES6, IE hasn't needed to work this way).
* Also works on strings, fixes IE < 9 to allow an explicit undefined
* for the 2nd argument (as in Firefox), and prevents errors when
* called on other DOM objects.
*/
(function () {
'use strict';
var _slice = Array.prototype.slice;

try {
// Can't be used with DOM elements in IE < 9
_slice.call(document.documentElement);
} catch (e) { // Fails in IE < 9
// This will work for genuine arrays, array-like objects,
// NamedNodeMap (attributes, entities, notations),
// NodeList (e.g., getElementsByTagName), HTMLCollection (e.g.,
childNodes),
// and will not fail on other DOM objects (as do DOM elements in IE <
9)
Array.prototype.slice = function(begin, end) {
// IE < 9 gets unhappy with an undefined end argument
end = (typeof end !== 'undefined') ? end : this.length;

// For native Array objects, we use the native slice function


if (Object.prototype.toString.call(this) === '[object Array]'){
return _slice.call(this, begin, end);
}
// For array like object we handle it ourselves.
var i, cloned = [],
size, len = this.length;

// Handle negative value for "begin"


var start = begin || 0;
start = (start >= 0) ? start : Math.max(0, len + start);

// Handle negative value for "end"


var upTo = (typeof end == 'number') ? Math.min(end, len) : len;
if (end < 0) {
upTo = len + end;
}

// Actual expected size of the slice


size = upTo - start;

if (size > 0) {
cloned = new Array(size);
if (this.charAt) {
for (i = 0; i < size; i++) {
cloned[i] = this.charAt(start + i);
}
} else {
for (i = 0; i < size; i++) {
cloned[i] = this[start + i];
}
}
}

return cloned;
};
}
}());
Especificaciones
Specification Status Comment

Initial definition. Implemented in


ECMAScript 3rd Edition Standard
JavaScript 1.2.

ECMAScript 5.1 (ECMA-262)


The definition of 'Array.prototype.slice' in that Standard
specification.

ECMAScript 2015 (6th Edition, ECMA-262)


The definition of 'Array.prototype.slice' in that Standard
specification.

Compatibilidad con navegadores


Desktop

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari

Basic support 1.0 1.0 (1.7 or earlier) (Yes) (Yes) (Yes)

Compatibilidad con navegadores

Mobile

Chrome for Firefox Mobile IE Opera Safari


Feature Android
Android (Gecko) Mobile Mobile Mobile

Basic
(Yes) (Yes) (Yes) (Yes) (Yes) (Yes)
support

You might also like