Careless Careless - 7 months ago 12
Javascript Question

Find word next to some symbol

If I have a

<textarea>
and I type
#SomeName is very happy today! #AnotherName
, I want to make
var name = #SomeName
or
#AnotherName
. I want to store in the
name
var only word that is next to
#
. Can someone tell me how to do it in jQuery?

Answer

Given that there could be an unlimited number of # values in the string within the textarea I would suggest you create an array to contain them all instead of a single string. With that in mind you can use a Regular Expression and the match() method. Try this:

var matches = textareaValue.match(/(^|\s)(#[a-z\d-]+)/ig);

Working example

The first part of the Regex is a negative lookahead to ensure the # is preceded by a space. The second part is retrieving the actual value.

Comments