Amila Jack
Amila Jack

Reputation: 87

Adding an attribute to a part of a string

I have the following string:

var string = "hello @johndoe how are you?";

how can I delimit the part of the string containing "johndoe" and add tags to, to get a result like this

"hello <div class="something">@johndoe</div> how are you?"

Upvotes: 0

Views: 54

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

I may go for a regex like

string = string.replace(/(@[^\s$]+)/g, '<div class="something">$1</div>')

Upvotes: 1

scrowler
scrowler

Reputation: 24406

You could do a replace:

string = string.replace('@johndoe', '<div class="something">@johndoe</div>');

This will only replace one instance though, to replace all you should use regex:

var re = new RegExp('@johndoe', 'g');
string = string.replace(re, '<div class="something">@johndoe</div>');

In a function:

function wrapDiv(string, accountName) {
    var re = new RegExp(accountName, 'g');
    string = string.replace(re, '<div class="something">' + accountName + '</div>');
    return string;
}

alert(wrapDiv('hello @johndoe and @mikesmith how are you?', '@johndoe'));

PHP isn't tagged in the question, but as per your comment - here's a PHP alternative (no need for regex here as str_replace() will replace all occurrences by default):

function wrapDiv($string, $accountName) {
    return str_replace($accountName, '<div class="something">' . $accountName . '</div>', $string);
}

$string = wrapDiv('hello @johndoe and @mikesmith how are you?', '@johndoe');
echo $string; // hello <div class="something">@johndoe</div> and @mikesmith how are you? 

Upvotes: 2

Related Questions