0

From the backend, I get JSON in the following format: <p>@username This is awesome.</p>

I have to detect @ in a word and then add a class to the entire word or a span so I can modify the word to something like this:

p span {
  font-weight: bold;
  color: red;
  }
<p><span>@username</span> This is awesome</p>

How do I detect using javascript to get this going? Please note that @ could be anywhere in the paragraph.

7

1 Answer 1

1

This bit of regex will find any word beginning with @ and wrap it (and the @) in a span tag.

var json = "{\"text\":\"<p>@username This is awesome.</p>\"}",
  text = JSON.parse(json).text;

text = text.replace(/(@\w+)/g, '<span>$1</span>');
console.log(text);

This will not work for email addresses. e.g. [email protected] will become a<span>@b</span>.com. Do you need a solution that takes this into account?

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.