Javascript: How to insert multiple blanks into a paragraph p element?

3

Good afternoon!

I'm inserting within a TAG HTML% with% some blanks, to complete the number of characters within a certain description (120).

I need white space to be visible on the page.

TAG :

<p>

However, I'm having a problem adding white space. I tried to use the ALT + 255 character, vulgar ' <p class="descricao">Exemplo de texto</p> ' , but the spaces are not being inserted, I also tried using ' ' but it did not work.

I did some testing, and when I replaced the white character with letters and numbers, it works normally.

Can anyone help?

Below is the Javascript code I'm using:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><pclass="descricao">Exemplo de texto</p>

<script>

var publicacoes = $( '.descricao' );

   for (var i = 0; i < publicacoes.length; i++)
   {
   var texto = publicacoes[i].textContent;
   var textoComplementar = "&nbsp;";

   for (var j = 0; j < (120 - texto.length); j++)
   {
        texto += textoComplementar;
   }

   publicacoes[i].textContent = texto;
   }

</script>
    
asked by anonymous 07.08.2018 / 20:14

2 answers

3

You can use innerHTML to be able to recognize &nbsp; but you will also have to increase size in for , because &nbsp; does not have a character, has 6 ...

Only recognizing spaces with innerHTML, however, only 15 spaces will be inserted:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><pclass="descricao">Exemplo de texto</p>

<script>

    var publicacoes = $('.descricao');
    var textoComplementar = "&nbsp;";

    for (var i = 0; i < publicacoes.length; i++) {
        
        for (var j = 0; j < (120 - publicacoes[i].innerHTML.length); j++) {
            publicacoes[i].innerHTML = publicacoes[i].innerHTML + textoComplementar;
        }

    }

</script>

Now leaving the text with 120 characters (only a change in the account location)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><pclass="descricao">Exemplo de texto</p>

<script>

    var publicacoes = $('.descricao');
    var textoComplementar = "&nbsp;";

    for (var i = 0; i < publicacoes.length; i++) {
        var restante = 120 - publicacoes[i].innerHTML.length;

        for (var j = 0; j < restante; j++) {
            publicacoes[i].innerHTML = publicacoes[i].innerHTML + textoComplementar;
        }

    }

</script>
    
07.08.2018 / 20:39
1

You can use the padEnd function to add the character you want when the defined size is not filled. Here we are defining that the text of our tag will be itself plus the character '' when the size of 120 is not met. "

$('#teste').text($('#teste').text().padEnd(120, ' '));

Do not forget to change the #teste to the id of your html tag.

    
07.08.2018 / 20:24