4

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 } console.log(addHtmlTag(string)) 

What will be the changes for adding html tag?

2
  • Probably you're not getting the expected output because the code crashes at const string = Lorem ipsum ? This is a syntax error Commented Oct 19, 2021 at 7:53
  • @JeremyThille I forgot to give "" in question Commented Oct 19, 2021 at 7:54

3 Answers 3

3

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(" ") console.log(replacedStr)

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

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

3 Comments

I always like your answers! Tricky!!! :)
Always glad to hear that man, thanks!
@SinanYaman That's the most elegant code I've ever seen :)
2

It can replace with regexp

 const str = 'Lorem ipsum dolor sit amet, #consectetur and #adipiscing' const result = str.replace(/#(\w+)\b/g, '<a href="/users/tag/$1">#$1</a>') console.log(result)

Comments

0

You missed Double qutes ("")

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

1 Comment

I guess that was just a copy paste error.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.