Métodos bacanudos para string

Allan Barbosa
allbarbos
Published in
2 min readNov 3, 2017

Não precisamos mais utilizar o indexOf para procurar string! o/

StartsWith
Ao utilizar este método podemos verificar se uma string inicia com determinado valor. Devemos passar a string que será procurada e a posição que começará a busca:

"Métodos bacanudos para string".startsWith("Métodos") // true
"Métodos bacanudos para string".startsWith("bacanudos", 8) // true

Lembrando que nem todos os browsers dão suporte a este recurso, sendo assim, para manter a compatibilidade existe o polyfill abaixo:

if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position) {
position = position || 0;
return this.indexOf(searchString, position) === position;
};
}

EndsWith
Contrário ao startsWith, compara se o final da string é igual ao informado. Caso queira comparar um pedaço, basta informar no segundo parâmetro o tamanho a ser considerado na string.

"Métodos bacanudos para string".endsWith("string") // true
"Métodos bacanudos para string".endsWith("bacanudos", 17) // true

O polyfill a ser usado caso o browser não possua suporte é:

if (!String.prototype.endsWith)
String.prototype.endsWith = function(searchStr, Position) {
if (!(Position < this.length))
Position = this.length;
else
Position |= 0;
return this.substr(Position - searchStr.length,
searchStr.length) === searchStr;
};

Includes
O includes é case-sensitivity e verifica se existe determinado valor dentro da string, podendo também passar o parâmetro informando onde iniciará a verificação:

"Métodos bacanudos para string".includes("para") // true
"Métodos bacanudos para string".includes("Para") // false
"Métodos bacanudos para string".includes("Métodos", 1) // false

Polyfill:

if (!String.prototype.includes) {
String.prototype.includes = function(search, start) {
'use strict';
if (typeof start !== 'number') {
start = 0;
}

if (start + search.length > this.length) {
return false;
} else {
return this.indexOf(search, start) !== -1;
}
};
}

Repeat
Como o nome já diz, o repeat nos retorna uma nova string de acordo com o número de repetição informado que pode ser entre 0 e infinito:

"Bacanudos".repeat(3) // "BacanudosBacanudosBacanudos"

Seu polyfill é:

if (!String.prototype.repeat) {
String.prototype.repeat = function(count) {
'use strict';
if (this == null) {
throw new TypeError('can\'t convert ' + this + ' to object');
}
var str = '' + this;
count = +count;
if (count != count) {
count = 0;
}
if (count < 0) {
throw new RangeError('repeat count must be non-negative');
}
if (count == Infinity) {
throw new RangeError('repeat count must be less than infinity');
}
count = Math.floor(count);
if (str.length == 0 || count == 0) {
return '';
}
if (str.length * count >= 1 << 28) {
throw new RangeError('repeat count must not overflow maximum string size');
}
var rpt = '';
for (var i = 0; i < count; i++) {
rpt += str;
}
return rpt;
}
}

--

--