Why doesn’t it work?
The following example defines two string variables. The variables contain the same string, except that the second string has uppercase letters. The first method log
has 19. However, as the method indexOf
is sensitive to box, the string "cheddar
" is not found in myCapString
, therefore the second method log
displays -1.
var myString = "brie, pepper jack, cheddar";
var myCapString = "Brie, Pepper Jack, Cheddar";
console.log('myString.indexOf("cheddar") é ' + myString.indexOf("cheddar"));
// Exibe 19
console.log('myCapString.indexOf("cheddar") é ' + myCapString.indexOf("cheddar"));
// Exibe -1
Source: String.prototype.indexof()
Alternative #1:
Force down box in his string
:
var name = 'CaRrO';
if(name.toLowerCase().indexOf("Carro".toLowerCase())!=-1) {
alert("existe");
} else {
alert("não existe");
}
Note that both the string
as to the searchValue
were in low box, which helps a lot in the dynamics.
Alternative #2:
Further improving the dynamics, you can create a function for this.
Take my example:
function in_str(string, value) {
string = string.toLowerCase();
value = value.toLowerCase();
if (string.indexOf(value) != -1)
return true;
else
return false;
}
console.log(
in_str('Carro', 'Carro'), // true
in_str('carro', 'CARRO'), // true
in_str('caRRo', 'carro'), // true
in_str('carro', 'caRRo'), // true
in_str('MoTo', 'caRRo'), // false
in_str('o Carro furou o pneu', 'caRRo') // true
);
Alternative #3:
The one I consider the best way and with even more dynamic, is to define a prototype to the class String
. Hence the use will be identical to the .indexOf
(except by the name of the method).
Take my example:
String.prototype.indexOfCaseIns = function(searchValue, fromIndex) {
return this.toLowerCase().indexOf(searchValue.toLowerCase(), fromIndex);
}
var str = 'Olá mundo!';
console.log(
str.indexOfCaseIns('MunDO'), // 4
str.indexOfCaseIns('world'), // -1
str.indexOfCaseIns('Olá'), // 0
str.indexOfCaseIns('ola'), // -1
str.indexOfCaseIns('OLá'), // 0
str.indexOfCaseIns('á munD'), // 2
str.indexOfCaseIns('undo!') // 5
);
Notice that it follows the same sense of indexOf
: returns -1
if not found or the index number of the searched value.
Applying in your code:
var name = $(".infoname").text();
if(name.indexOfCaseIns("Carro")!=-1) { // só trocar o método ;D
alert("existe");
} else {
alert("não existe");
}
name
is what?– LipESprY
you can use var name = "car"
– Josimara
name is currently var name = $(".infoname"). text();
– Josimara
I did a little reworking on the question. If you find it inappropriate, you can revert to revision. ;D
– LipESprY