0

Recently, I built a chat. The linkification of content typed into the textarea created some trouble.

 if(!String.linkify) {
            String.prototype.linkify = function() {

                // http://, https://, ftp://
                var urlPattern = /\b(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|]/gim;

                // www. sans http:// or https://
                var pseudoUrlPattern = /(^|[^\/])(www\.[\S]+(\b|$))/gim;

                // Email addresses
                var emailAddressPattern = /[\w.]+@[a-zA-Z_-]+?(?:\.[a-zA-Z]{2,6})+/gim;

                return this
                    .replace(urlPattern, '<a href="$&">$&</a>')
                    .replace(pseudoUrlPattern, '$1<a href="http://$2">$2</a>')
                    .replace(emailAddressPattern, '<a href="mailto:$&">$&</a>');
            };
        }
  1. Problem: Links in chatlog were not transformed, but appear a pure string.
  2. Problem: Links contain hidden characters â£https://www.link.com/product/ABC/myaffiliatelink When i called the resulting links, I got the following browser notification:
  Not Found
    The requested URL â£https://www.link.com/product/ABC/myaffiliatelink was not found on this server.

To get the message, I use:

textContainer.textContent = message.linkify();

Can somebody explain what happens and how to fix this?

Nixen85
  • 1,253
  • 8
  • 24
  • 1
    You need to post your code for us to have any chance of figuring out what's wrong. – Barmar Mar 07 '18 at 17:57
  • 1
    You can use either [docker secrets](https://docs.docker.com/engine/swarm/secrets/#about-secrets) or [something like this](https://medium.com/@basi/docker-environment-variables-expanded-from-secrets-8fa70617b3bc) using env variables. But as @Barmar said, you have to provide lot more info, at least some code to be able to help you – Franco Papalardo Mar 07 '18 at 18:07
  • 1
    Can you give me a directly applicable example? I'm a little confused as to how 'something' translates into an affiliate link. Maybe you want to track what links people click on or are you just trying to remove portions of the link? – Neil Mar 07 '18 at 22:51

1 Answers1

2

After thinking and playing a while with the code, I got the answer. When I use

textContainer.textContent = message.linkify();

I define the result as pure string. In consequence my linkify function, which adds html-elements such as <a href=""> is then interpreted as string and thus fails.

The solution is to change the call into

textContainer.innerHTML = message.linkify();

As a result, the elements are interpreted as html-elements and can be extended. More infos about differences between innerHTML and textContent can be found here.

Best regards, Joe.

Nixen85
  • 1,253
  • 8
  • 24