Handle exception when doing replace of string via JavaScript

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 does a replace in my html and inserted the links as desired.

But now I need to handle some cases and I could not think of a simple way to solve it.

Basically the cases I need to deal with are:

  • Do not convert string to link when inside another link.
  • Do not convert string to link when value is one tag attribute.

The html that I perform find and replace, I get:

<p><a class="btn" href="http://www.google.com.br/">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.br/" 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;
    }
};

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

Any suggestions how to resolve this?

    
asked by anonymous 28.08.2015 / 18:37

1 answer

1

I made an example with comments.

The logic is simple ...

  • You save the existing tags in a separate array

  • Replace all "word" with "wordWithTag"

  • 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.br!!!!!!/">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.br/" 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));
        
    03.09.2015 / 14:47