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.

Elaine Byene
  • 3,868
  • 12
  • 50
  • 96
  • 2
    Possible duplicate of [Is there a CSS selector for elements containing certain text?](https://stackoverflow.com/questions/1520429/is-there-a-css-selector-for-elements-containing-certain-text) – Andy Ray Nov 01 '18 at 15:46
  • How is the JSON being passed in? – dmikester1 Nov 01 '18 at 15:49
  • https://duckduckgo.com/?q=stackoverflow+javascript+at+mention+regex – str Nov 01 '18 at 15:49
  • @AndyRay No. It's not. I have made changes to the question. – Elaine Byene Nov 01 '18 at 15:56
  • @dmikester1 It's on Angular and so using html-bind. The output after parsing is what is shown in the question. – Elaine Byene Nov 01 '18 at 15:57
  • Interesting problem! Twitter @bombs? Will there ever be an instance where there's an email in the paragraph string? Then you would need to detect the difference between an @bomb and an email – Mathias Rechtzigel Nov 01 '18 at 15:58
  • @MathiasRechtzigel Interesting. Had not thought about an email perspective! Thanks. I found a solution using regex js. Will post an answer if i find something. Thanks. – Elaine Byene Nov 01 '18 at 16:04

1 Answers1

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. a@b.com will become a<span>@b</span>.com. Do you need a solution that takes this into account?

Richard Parnaby-King
  • 14,703
  • 11
  • 69
  • 129