0

I'm building an ionic app that lets users chat between each other.

In the event of a user sending a url as plain text, I have a function called urlify that replaces the text with html, and when a user clicks on the html for the url it should take them to that url.

The problem is, anchor elements don't open urls in Ionic, so I have to use window.open(url)..

Here is my code:

urlify(text) {
  if(text) {
    var urlRegex = /(https?:\/\/[^\s]+)/g;
    return text.replace(urlRegex, function(url) {
        return '<span class="message-link">' + url + '</span>';
    })
  }
}

openLink(url) {
  window.open(url, '_system')
}

So when a user clicks the span it should open openURL but since I can't add (click)="openURL(url)" to the dynamically generated html, I'm not sure what to do..

Any ideas? Thank you!

2
  • @ABOS because it's user generated text so if someone adds a url as plain text eg google.com I need to convert it to a hyperlink so that it's clickable Commented Jan 23, 2019 at 20:16
  • this might help stackoverflow.com/questions/48028676/… Commented Jan 23, 2019 at 20:23

1 Answer 1

0

This can help you, you can add anything dynamically on this way.

urlify(text) {
  if(text) {
    var urlRegex = /(https?:\/\/[^\s]+)/g;
    return text.replace(urlRegex, function(url) {
        let newElement = document.createElement('span');
        newElement.innerHTML = url
        newElement.classList.add('message-link');
        newElement.onclick = function() {
            window.open(url, '_system')
        }
        return newElement
    });
  }
}

You can return this newElement or append it here, for example document.getElementById('someDivID').append(newElement) on this way

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.