I need help identifying twitter handles (I think it’s called a handle..) inside plain-text sentences and wrap a span tag around the handle.
So if I have a sentence constructed like this:
I can't wait to watch the 2012 London Olympic Games! @london2012
I need to find the handle and wrap a span tag around it:
I can't wait to watch the 2012 London Olympic Games! <span>@london2012</span>
Here is what I attempted with:
function findHandle(text) {
var handle = text.substr(text.indexOf("@"), text.indexOf(" "));
return text.replace(handle, "<span>" + handle + "</span>");
}
My code isn’t working as planned. What would be the best approach to this?
Assuming that your text-content is in a
divelement, the following seems to work (though not tested exhaustively):JS Fiddle demo.
The above seemed a little fragile, so I’ve changed the regex selector to:
JS Fiddle demo.
References:
html().string.replace().