Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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 <code>@</code>) before a user name, so that they can elect whether or not to have a link to the user...</p> <p>Aside from that, your expression has several potential errors: character classes (denoted by <code>[]</code>) treat nearly all characters literally, including <code>|</code>, the entire alternation syntax makes the third alternation (<code>(\s(user))</code>) into something that will allow matches to <code>userSmith</code> or <code>userJones</code> and not just <code>user</code> - which is something I think you specifically want to disallow...</p> <p>I think you are asking for something like this:</p> <pre><code>(^|\s)(user)(?=[:;,\s]|$) </code></pre> <p>this breaks down to:</p> <pre><code>(^|\s) # either assert that this is the beginning, or capture a whitespace character; capture into back-reference #1 (user) # capture the username 'user' exactly (?= # look-ahead to verify that the following CAN be matched [:;,\s] # one character that is : ; , &lt;or whitespace&gt; | # -OR- $ # the end of the string ) # end look-ahead </code></pre> <p>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: <code>Let me know if you see user.</code>, <code>have you seen user?</code> or <code>I really like user!</code> - the rejection for URLs should already be accomplished by requiring whitespace (or the beginning of the string) before <code>user</code> - not allowing such punctuation afterwards will reject some cases I think you will want to match. You could simply add in this extra punctuation:</p> <pre><code>(^|\s)(user\b)(?=[;:,.?!)"\s]|$) </code></pre> <p>But I would suggest something more like the following (removing the following-punctuation requirement):</p> <pre><code>(^|\s)(user\b) </code></pre> <p>I've put all three suggestions on <a href="http://jsfiddle.net/dWVWz/1/">jsFiddle</a>, to show you what you get and allow you to put some of your own strings in.</p> <p>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:</p> <pre><code>source.replace(/(^|\s)(user\b)/gi, '$1&lt;a href="/linkToProfile?n=$2"&gt;$2&lt;/a&gt;') </code></pre> <p>Though I'm pretty sure I answered the question, please let me know if there are cases you specified that aren't covered!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload