Compare if a string contains a word

1

I have the following problem

I need to do an if that compares if a word is inside a string separated by spaces, and that is not sensitive to mayus / minus.

var name = "Lupa 163";
 
 if (name == 'lupa'){
     console.log("Es verdad");
}
else{
  console.log("Es mentira");
}
    
asked by Tefef 21.12.2018 в 09:06
source

2 answers

3

You could use includes() javascript to see if the string contains what you need and the toUpperCase() or toLowerCase() to desensitize the string.

var name = "Lupa 163";
name = name.toUpperCase();
 
if (name.includes(' LUPA ')){
     console.log("Es verdad");
}
else{
  console.log("Es mentira");
}

name = " Lupa 163";
name = name.toUpperCase();
if (name.includes(' LUPA ')){
     console.log("Es verdad");
}
else{
  console.log("Es mentira");
}
    
answered by 21.12.2018 / 09:52
source
1

What you're guessing I think is the function .search() would be something like this:

var text = "EnCuEnTrA La PaLaBrA";

//normalizando
text = text.toLowerCase();
text = text.trim();

$("#output").append("Primera busqueda : ");
if (text.search("     palabra    ".trim()) != -1)
    $("#output").append("verdad");
else
    $("#output").append("mentira");
    
$("#output").append("<br/> Segunda busqueda : ");
    
if (text.search("nada") != -1)
    $("#output").append("verdad");
else
    $("#output").append("mentira");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output">
</div>

This function returns the position of the word you are looking for and if it is not present it returns -1.

for the case sensitive you could use txt.toUpperCase() or txt.toLowerCase() to normalize the fragments and for more security you could use the function txt.trim() to avoid having extra spaces

I hope it helps you

    
answered by 21.12.2018 в 09:52