Scroll through text and link word - Jquery

Asked

Viewed 77 times

0

It is possible to select words in a long text and link them?

Example: I want to select and link the words: donkey and walk.

Note: Only 1 time, no repetition of links and each word for a different link:

    O menino quer um burrinho
    para passear.
    Um burrinho manso,
    que não corra nem pule,
    mas que saiba conversar
    O menino quer um burrinho
    para passear.

Exit:

O menino quer um **burrinho**
para **passear**.
Um burrinho manso,
que não corra nem pule,
mas que saiba conversar
O menino quer um burrinho
para passear.

The bold (asterisks) are the links.

  • You need to enter all the information to receive a reply, the text is where, is always the same text, at which time you will want "link" the words, and what would link words?

  • What would be "select"? How would this selection be made?

2 answers

1

You can use .replace to find the word and manipulate it.

var texto = $('p').text().replace('burrinho', '<strong>burrinho</strong>').replace('passear', '<strong>passear</strong>');

$('p').html(texto);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>O menino quer um burrinho
    para passear.
    Um burrinho manso,
    que não corra nem pule,
    mas que saiba conversar
    O menino quer um burrinho
    para passear.</p>

  • .replace you will find the first searched value if you pass a simple string, e.g.: using 'donkey' in the search, it will only work for the first dumb word you find. If you want all the words 'donkey' to suffer action, it is necessary to use Regex, ex: `.replace(/donkey/g, '<Strong>donkey</Strong>')

  • Perfect. That’s what I wanted.

1


You can do this without using jQuery, just with replace, because the replace only replaces the first occurrence you encounter.

As the question does not indicate how the words are selected, in the example below I created an array with the two words and made a loop for to search each one and replace it with a link <a>:

let texto = `O menino quer um burrinho
    para passear.
    Um burrinho manso,
    que não corra nem pule,
    mas que saiba conversar
    O menino quer um burrinho
    para passear.`;

const palavras = "burrinho passear".split(" ");

for(let p of palavras){
   texto = texto.replace(p, `<a href="#${ p }">${ p }</a>`);
}

document.getElementById("texto").innerHTML = texto;
<div id="texto"></div>

  • That’s right, in case I’m picking up a text that is within a span with class . text, I’m not understanding how I can adapt this for.

  • Managed to make?

  • I couldn’t. I don’t understand how I can adapt since my text is inside a class=text and for uses the text Let.

  • Would be several class=text or just one?

  • Single <span class=text> SEVERAL PARAGRAPHS INSIDE </span>

  • Then it would be: let texto = $(".texto").text();.

Show 1 more comment

Browser other questions tagged

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