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') */
Then we turn this text into array.
let tweetArr = tweet.split(" ")
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>'
}
}
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 */
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)