将属性添加到字符串的一部分

时间:2014-09-01 04:45:50

标签: javascript jquery

我有以下字符串:

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

如何划分包含" johndoe"的字符串部分?并添加标签,以获得像这样的结果

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

2 个答案:

答案 0 :(得分:2)

你可以做一个替换:

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

这只会替换一个实例,以替换所有你应该使用的正则表达式:

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

在一个功能中:

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没有在问题中标记,但根据您的评论 - 这里是PHP替代方案(此处不需要正则表达式str_replace()将替换默认情况下的所有匹配项):

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? 

答案 1 :(得分:1)

我可能会选择像

这样的正则表达式
string = string.replace(/(@[^\s$]+)/g, '<div class="something">$1</div>')