I’m trying to match usernames within a string like:
"user: hi, has anyone seen user today user"
The cases to match:
- substring is the first word trailing a space, in the middle surrounded by spaces or the last and leading a space
- Following characters are allowed to trail the word but not returned as a result: “:;,”
The following matches all the cases but returns unwanted spaces and characters (I only want to replace usernames):
/(^(user)[\s|:|;|,])|(\s(user)[\s|:|;|,]?\s)|(\s(user))/gi
In the end I want to replace only username with links.
EDIT: Note that the username can’t be matched if it’s part of url or other string, except cases when special characters are trailing it.
Depending upon how transparent you want it to be to users (or what your eventual goal is), you may consider requiring someone to put a symbol (such as
@) before a user name, so that they can elect whether or not to have a link to the user…Aside from that, your expression has several potential errors: character classes (denoted by
[]) treat nearly all characters literally, including|, the entire alternation syntax makes the third alternation ((\s(user))) into something that will allow matches touserSmithoruserJonesand not justuser– which is something I think you specifically want to disallow…I think you are asking for something like this:
this breaks down to:
However, there are a few cases that you might want to consider. By not allowing several types of punctuation after the username, you will exclude results from strings like:
Let me know if you see user.,have you seen user?orI really like user!– the rejection for URLs should already be accomplished by requiring whitespace (or the beginning of the string) beforeuser– not allowing such punctuation afterwards will reject some cases I think you will want to match. You could simply add in this extra punctuation:But I would suggest something more like the following (removing the following-punctuation requirement):
I’ve put all three suggestions on jsFiddle, to show you what you get and allow you to put some of your own strings in.
Which ever way you prefer, these expressions would be used in a find-replace wherein you would replace the whitespace consumed before the user’s name with itself in the replace expression:
Though I’m pretty sure I answered the question, please let me know if there are cases you specified that aren’t covered!