How can I find a word in a text or in an object with javascript?
I thought I would use for
loop. How would you do that?
How can I find a word in a text or in an object with javascript?
I thought I would use for
loop. How would you do that?
That depends a lot on how your scenario is.
If you want to find out if a string contains a given data, you can check it with indexOf
or using match
.
Example:
var texto = "eu sou programador javascript";
var contemTexto = texto.indexOf("programador") > -1 ? true : false;
The indexOf
will return the "INDEX" containing that text, if it does not, the result is -1
as default.
The match
it returns a array
with the word you are looking for.
Example:
var texto = "Eu sou programador javascript";
var resultado = texto.match("programador");
Now the result is, array
with all developer occurrences in that phrase. In the case above, it only exists 1x, but if it was a big sentence, it would return every time:)