views:

323

answers:

2

I'd like to surround all words in a haystack starting with @ with <b> tags with javascript regex. What pattern would I use?

+5  A: 
var sample = "@sample";
sample = sample.replace(/(^|\s|-)+@(\w+)/g, "<b>$&</b>");
//^^that's assuming you want the @ to stay
//if not, use $2 instead of $&

$& inserts the matched substring.

Using functions:

var sample = "@sample";
sample = sample.replace(/(^|\s|-)+@(\w+)/g, function(str) {
    return "<b>"+str+"</b>";
}

Using functions is a good idea when you want to have greater or finer control. You might want to process the current matched piece. Whatever you want.

See more here at MDC.

geowa4
Now I don't really know if `\w+` will match the strings you want, but if you have a regex problem, that's proper for another question.
geowa4
Also, put a "g" after the regular expression to match all occurrences, like: /@\w+/g
edsoverflow
yeah, i seemed to have realized that as you were commenting. thanks
geowa4
A: 

George's example will match everything after @, including [email protected]. Try:

function BoldMyText(text) {
    var words = text.split(" ");
    var returnText = '';

    for(var i=0;i<words.length;i++) {
         word = words[i].replace(/^@(\w+)/, '<b>$1</b>');
         returnText += ' ' + word;
    }

    return returnText;
}

var myBoldedText = BoldMyText("You should @not bold [email protected]");

If its not what you want.

Nathan