Javascript string?

Asked

Viewed 42 times

0

How do you know the number of times a letter appeared in a Javascript sentence?

Example:

palavra = "a"

frase = "Agora vai!"

As shown on the console the number of times string "a" appeared in the phrase "Now go!" ?

  • did you make any example of code? ever heard that a text is a array letter, that is, each word of a text has a position?

  • 1

    Here has some solutions, just adapt to your case

1 answer

1

The fatherly way is to read each position of that string and check the match, example:

var test = 'a';
var texto = "stackoverflow pt-brasil";
var busca = 0;
for(let i = 0; i < texto.length; i++) {
  if (texto.charAt(i) === test) {
    busca++;
  }
}
document.getElementById("resultado").innerHTML = `Encontrou: ${busca}`;
console.log(busca);
<div>
  <div><b>Texto:</b> stackoverflow pt-brasil</div>
  <div><b>Palavra de Busca:</b> a</div>
  <div id="resultado"></div>
</div>

If using the method match with regex simplifies the code well:

// busca todos com a letra 'a' independente de ser maiúsculo ou minúscula  
var test = /a/g; 

var texto = "stackoverflow pt-brasil";
var busca = texto.match(test);

document.getElementById("resultado").innerHTML = `Encontrado: ${busca.length}`;
console.log(busca.length);
<div>
  <div><b>Texto:</b> stackoverflow pt-brasil</div>
  <div><b>Palavra de Busca:</b> a</div>
  <div id="resultado"></div>
</div>

this second form brings a array with all correspondence.

Another way too for of:

// busca todos com a letra 'a' independente de ser maiúsculo ou minúscula  
var test = 'a'; 
var texto = "stackoverflow pt-brasil";
var count = 0;

for(l of texto) {
  if (l === test) {
    count++;
  }
}

document.getElementById("resultado").innerHTML = `Encontrado: ${count}`;
console.log(count);
<div>
  <div><b>Texto:</b> stackoverflow pt-brasil</div>
  <div><b>Palavra de Busca:</b> a</div>
  <div id="resultado"></div>
</div>

Other examples on the site itself

  • 1

    @Augustovasques I did the editing, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.