我有以下字符串:
var string = "hello @johndoe how are you?";
如何分隔包含“johndoe”的字符串部分并添加标签,以获得这样的结果
"hello <div class="something">@johndoe</div> how are you?"
最佳答案
您可以进行替换:
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?
关于javascript - 将属性添加到字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25598968/