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

标签 javascript jquery

我有以下字符串:

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/

相关文章:

javascript - 如何让 jQuery Maphilight 工作?

javascript - AngularJS ng-switch 或类似的工具来处理动态值

javascript - 如何提醒用户 Chrome 应用程序更新?

javascript - 在没有源代码或构建过程的 Electron 应用程序的生产构建中打开 Chromium DevTools

javascript - 如何将滚动条滚动到页面中央?

jquery 函数外部变量

javascript - 如何将值从 HTML 表单提交传递到 Google 表格并返回到 Google Apps 脚本 Web 应用程序中的 HTML

javascript - IIFE 内部的函数无法识别

jquery - Spring Security Core authAjax,如何忽略 Referer

javascript - Jquery Plugin qTip2 这是在 Hypem.com 上使用的吗?