How to concat string and add html tag to it?

I have string something like:

Lorem ipsum dolor sit amet, #consectetur and #adipiscing 

I want to add html tag for hashtags which are present in the string. Expected Output is:

Lorem ipsum dolor sit amet, <a href="/users/tag/consectetur">#consectetur</a> and <a href="/users/tag/adipiscing">#adipiscing</a>

I am using javascript string operator split() and join(), but I am not getting the expected output.

    const string =  "Lorem ipsum dolor sit amet, #consectetur and #adipiscing" 
    function addHtmlTag(string){
       string = string.split("#").join('<a href="#/users/tag/">#</a>');
    return string

What will be the changes for adding html tag?


You can use something like this:

const str = "Lorem ipsum dolor sit amet, #consectetur and #adipiscing"

const replacedStr = str.split(" ").map(word => (
  word[0] === "#" ? `<a href="/users/tag/${word.split("#")[1]}">${word}</a>` : word
)).join(" ")


This searches for words that starts with "#" and append the a tag based on the word.