How to break string by replacing space by line break

0

I need to Break a String in the appropriate white space, so that the line break is inserted in the place of the space \n escape character in>, in order that this jump line-by-line. Here's an example Logic below:

  

Casa Bonita

It looks like this:

  

Home

     

Pretty

For more details, see what I have achieved so far, but I want to do something more ...

<script>
    window.onload=function(){
      campo = "Casa Bonita"
       letra = campo.split(" "); // Quebra Linha no Espaço
       for(var i in letra)
      alert(letra[i]);
    }
</script>

Well, what is this something more ../ result being displayed in alert line after row successively according to the size of the String. However, I would like to skip each line using \n and not <br> within innerHTML(); . Get help!

    
asked by anonymous 07.04.2016 / 15:20

2 answers

8

You can use a regular expression to replace all blanks.

var texto = "minha linda casa branca".replace(/\s/g, "\n");
alert(texto);

P.S: \s is the metacharacter for whitespace.

To make a sort of the words, you will need to store the words in an array, then make the luck and finally make a join.

var texto = "minha linda casa branca";
var palavras = texto.split(" ");
var collator = new Intl.Collator('pt-BR', { sensitivity: "base" });
palavras.sort(function (paravra1, palavra2) {
  return collator.compare(paravra1, palavra2)
})
texto = palavras.join("\n");
alert(texto);

I used Intl.Collator with { sensitivity: "base" } , so when comparing strings, case and acentos are "ignored", in this case a ≠ b , a = á , a = A .

    
07.04.2016 / 15:36
2

Well, your contribution has helped me, now I have done my work, so that I can stay for future analysis and study by other users who, like me, have the same doubt. See:

texto = "Bruna Dora Carla Amanda Emiliana"
letra = texto.split(" ");
letra.sort();
texto = letra.join("\n");
alert(texto);
    
07.04.2016 / 20:44