0

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?"
0

2 Answers 2

2

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? 
Sign up to request clarification or add additional context in comments.

3 Comments

The string is outputted with php so @johndoe isn't a variable in js. Is it possible to do this dynamically?
Why don't you do it with PHP then?
The issue is that the username is not inserted dynamically with php. Comments are saved as plain text. In the DB, a row would have "hello @johndoe how are you?"
1

I may go for a regex like

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

5 Comments

This looks good aswell if you're trying to target all @ keywords.
@arun /(@[^\s$])/ will only replace one character. It should have a '+'. like: /(@[^\s]+)/ or /(@[^\s$]+)/
@DrGeneral yes... copied the wrong version from my console :(
How can I use this method to get just "amilajack"? That would also be really helpful! Thank you so much!
@AmilaJack name = string.match(/@([^\s$]+)/)[1]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.