Validate if the string has a certain character [JQUERY]

1

I need to input an input string such as "Jose_Silva", how do I validate if the string has "_" in it.

    
asked by anonymous 16.06.2018 / 16:54

2 answers

3

indexOf () - returns the position of the first occurrence of a specified value in a string, otherwise returns -1 .

var string = "Jose_Silva";
if (string.indexOf('_') > -1)
{
  console.log("contém");
}

You can also use the includes method of ES6

  

The includes() method determines whether a string can be found inside another string, returning true or false. The includes() method is case sensitive.

var str = 'Jose_Silva';

console.log(str.includes('_'));
    
16.06.2018 / 17:16
1

You can use regular expressions,

if (/_/.test(minhaStringAProcurar)) {
    alert(minhaStringAProcurar + ' contém _');
}

that make it easy to manipulate string (and understanding the code once you get used to it). For example, if you get an occurrence of _ in your string, you will probably manipulate it, break it into parts, or replace the character with something,

// Com esta linha abaixo, substituo em minhaStringAProcurar
// todas a ocorrências de _ por dólar, e atribuo o resultado
// de volta a minhaStringAProcurar.
minhaStringAProcurar = /_/gm.replace(minhaStringAProcurar, 'dólar')

Regular expressions, as the name says, allows you to represent a string of well-defined string occurrence patterns with a language appropriate for that. It's a powerful feature, which can save code writing time considerably:

var resultado = '';
var ocorrenciasDeTextoNoHollerith = /\w+/gm.match(hollerithOriginal)
for (var i = 0; i < ocorrenciasDeTextoNoHollerith.length; ++i) {
    if (resultado !== '') resultado += ', ';
    resultado += ocorrenciasDeTextoNoHolerith[i];
}
alert(resultado);
    
16.06.2018 / 17:06