3

Im trying to add a span tag + classname around a word that contains the @ char.

My current piece of code only returns a true value if it is found, unfortunately I have no idea how to add the tag + classname. What's a proper way to do this?

var string = "hello @peter how are you?", substring = "@";
  if (string.indexOf(substring) > -1){
     //add span tag + classname around @peter 

  }

endresult should change the variable to this:

var string = "hello <span class='mentioned'>@peter</span> how are you?"
Richard Avalos
  • 555
  • 5
  • 18
  • 1
    Other than [**Tony the Pony**](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags#answer-1732454), this seems to be a duplicate of [**this**](http://stackoverflow.com/questions/12824928/jquery-wrapping-a-string-that-matches-a-regex) – adeneo Jan 03 '16 at 22:27

1 Answers1

3

One option would be to use the .replace() method. The expression (@\S+) is a capturing group that matches the @ character literally, followed by one or more non-white space character(s). Since $1 represents the first capturing group, the match is simply replaced with <span class='mentioned'>$1</span>, which essentially wraps the match.

var string = "hello @peter how are you?";
string = string.replace(/(@\S+)/g, "<span class='mentioned'>$1</span>");

// "hello <span class='mentioned'>@peter</span> how are you?"

However, depending on the input, it may actually just be better to use \w rather than \S. In doing so, only the characters [A-Za-z0-9_] will be matched (rather than everything other than any non-white space character).

For instance:

var string = "hello @peter97... how are you?";
string = string.replace(/(@\w+)/g, "<span class='mentioned'>$1</span>");

// "hello <span class='mentioned'>@peter97</span>... how are you?"
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304