DEV Community

Cover image for Transfer @handler & Hashtags in text into clickable links - JavaScript
Humaidan Hamad
Humaidan Hamad

Posted on

Transfer @handler & Hashtags in text into clickable links - JavaScript

In this article we will see how transfer any word inside a text start with special character like hashtags or @ handler, you can use this JavaScript method.

First we declare the tweet text variable either from the Dom element or a single string text;

let tweet = 'Hello World @twitter #GoodDay'; /* Or document.getElementById('tweetDiv') */
Enter fullscreen mode Exit fullscreen mode

Then we turn this text into array.

let tweetArr = tweet.split(" ")
Enter fullscreen mode Exit fullscreen mode

Now we loop through this array to match and attach links to each string start with '@' or '#'.

for(let i = 0; i < tweetArr.length; i++){
    let SelectedTweet = tweetArr[i];
    if(SelectedTweet.startsWith('@')){
      tweetArr[i] = '<a href="https://twitter.com/'+SelectedTweet+'">'+SelectedTweet+'</a>'
    } else if(SelectedTweet.startsWith('#')){
      tweetArr[i] = '<a href="https://twitter.com/search?q=%23'+SelectedTweet+'">'+SelectedTweet+'</a>'
    }
}
Enter fullscreen mode Exit fullscreen mode

And then we insert the updated text to the Dom element after we convert the Array into Text.

tweet = tweetArr.join(" ")
console.log(tweet);
/* Or document.getElementById('tweetDiv').innerHTML = tweet */
Enter fullscreen mode Exit fullscreen mode

And that how we transfer text start with @ or Hash into Twitter style links, Hope this simple tutorial help you get a better understand of how these things done.

Top comments (0)