Use Regex to replace text

Asked

Viewed 82 times

-1

I need to display a text and replace a few words with a field of the type input. The idea is that it fills in this input the word that was hidden. It’s like a guessing game.

So let’s assume I have the following text: "Lorem ipsum dolor sit Amet, consectetur adipiscing Elit."

I want to hide the word "ipsum" from this text, causing a field input appear in her place.

I thought of marking the word using the signs << >>, this way I could use regex to find these characters, and then replace this content with Jquery. I think the site https://regexr.com/ does just that.

The problem is that I have no idea what kind of regular expression to use to do this. Actually, I don’t even know if that’s possible.

I don’t even have a code approximate to that because I’ve never used regular expressions. The only thing I have so far is this:

var text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";

var search = "lorem";

var match = search.split(" ").every(function (word) {
    var regex = new RegExp(word, "i");
    return regex.test(text);
});

if (match) {
    alert("String '" + search + "' Encontrada.");
}

1 answer

1

At first, you could simply create HTML with the text and the input, but if the idea is that it is dynamic, an alternative would be:

var p = document.querySelector('#texto');
document.addEventListener('DOMContentLoaded', function() {
    var text = p.innerText; // pega o texto
    var palavra = 'ipsum'; // palavra a ser substituída
    // procura pela palavra
    var regex = new RegExp(`\\b${palavra}\\b`);
    var match = regex.exec(text);
    if (match) { // se encontrou
        p.innerHTML = ''; // limpa o elemento

        // cria textnodes com os trechos antes e depois da palavra, e também o input
        p.appendChild(document.createTextNode(text.slice(0, match.index))); // texto antes da palavra

        var input = document.createElement('input');
        input.size = palavra.length;
        p.appendChild(input);

        p.appendChild(document.createTextNode(text.slice(match.index + palavra.length))); // texto depois da palavra
    }
});
<form>
  <p id="texto">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</form>

That is, the regex searches for the word, taking care to use the shortcut \b (the word Boundary), to avoid taking parts of a word (for example, if the phrase is "Beware of the die", the word is "given" and regex does not use \b, the "die" of the word "Care" would be found and replaced; already using \b i guarantee that regex picks up the word "given" correctly). The same problem would occur if I used text.indexOf(palavra), for example (which would be a solution without regex, if it did not have this problem of picking up parts of a word).

Remember also that I’m only catching the first occurrence (if the word occurs more than once, will only catch the first).

Then I pick up the paragraph text (I put the text in an element to make it easier to find and manipulate it), and how the match has the position in which the word is, I can pick up the snippets before and after the word. Then just create text nodes with these texts, in addition to the input, and insert everything into the element that originally had the full text.

And about creating the RegExp using any word, it’s worth this reading.

Browser other questions tagged

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