Treat exception when replacing string via Javascript

Asked

Viewed 301 times

1

I created a simple Javascript function to replace any string with a link within an area in my html. Until then I pass some parameters and this function replaces in my html and inserted the links as desired.

But now I need to handle some cases and I couldn’t think of a simple way to solve.

Basically the cases I need to deal with are:

  • Do not convert the string to link when inside another link.
  • Do not convert the string to link when it is the value of a tag attribute.

The html I perform find and replace, I get this way:

<p><a class="btn" href="http://www.google.com/">Mecanismo de Busca</a>, loren ipsun dolor loren Google.</p>
<p>Loren ipsun dolor loren Google, loren ipsun dolor <span>Loren</span>, <b>Google</b>.</p>
<p>Acesse o <a class="btn" href="http://www.google.com/" title="Acesse o Google">Google</a></p>

My job is this:

var jsLib = {
    replaceToHref: function (word, url, target) {
        var wordWithTag = '<a href="' + url + '" title="' + word + '" target="' + target + '">' + word + '</a>'
        var content = document.getElementById('page-content-replace');

        var result = content.innerHTML.replace(new RegExp("(\\s|\\.|\\-|^|;|\\!|\\?|\\(|\\)|\\:|\\\\)(" + word + ")(\\s|\\.|\\-|^|;|\\!|\\?|\\(|\\)|\\:|\\\\)", "g"), "$1" + wordWithTag + "$3");

        content.innerHTML = result;
    }
};

Considering the html received and the function, when executing and passing the link and the word Google, it changes everywhere, however this breaks the html.

Any suggestions on how to fix this?

  • have as for example the cases you do not want to convert?

  • it is possible to create an array with the positions of everything you want to change, and create another array with the positions of everything that should not be changed, and validate when doing replace

1 answer

1

I made an example with comments.

The logic is simple...

  1. Vc saves existing tags in a separate array

  2. Replace all "word" with "wordWithTag"

  3. Back with pre-existing tags for the place

To reserve the space of each original tag, I used the string: {{PLACEHOLDER_TO_OLDS_TAGS_A}}

var target = '<p><a class="btn" href="http://www.google.com!!!!!!/">Mecanismo de Busca</a>, loren ipsun dolor loren Google.</p>'
+ '<p>Loren ipsun dolor loren Google, loren ipsun dolor <span>Loren</span>, <b>Google</b>.</p>'
+ '<p>Acesse o <a class="btn" href="http://www.google.com/" title="Acesse o Google">Google</a></p>';



function replaceToHref(word, url, target){
        //Espaço o reservado para as as tags "a" já existentes
        var placeHolder = '{{PLACEHOLDER_TO_OLDS_TAGS_A}}';
        //Regex para a tag "a"
        var matchTagA = /<a.*?>.*?<\/a>/g;


        //Cria a tag
        var wordWithTag = '<a href="' + url + '" title="' + word + '">' + word + '</a>\n';
        //Escapa string a ser buscada
        var wordEscaped = word.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");

        //Cria um array com todos os "a" já existentes
        var oldLinks = target.match(matchTagA);
        //Remove todas as tags "a"
        var targetWithoutTagA = target.replace(matchTagA,placeHolder);
        // Substitui todas as ocorrências da palavra pela tag
        var newTarget = targetWithoutTagA.replace(new RegExp(wordEscaped, 'gi'), wordWithTag);

        //Verifica se "oldLink" é um array e se tem algo, pois pode ser que o target não tenha nenhuma tag "a"
        if(Array.isArray(oldLinks) && oldLinks.length){
                //Dá um replace em uma ocorrência por vez coincidindo com o a posição anterior
                for(var i = 0;i < oldLinks.length; i++){
                        newTarget = newTarget.replace(placeHolder,oldLinks[i]);
                }
        }

        return newTarget;
}

console.log(replaceToHref('google','abc',target));

Browser other questions tagged

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