使用javascript替换另一个字符串中的字符串

使用javascript替换另一个字符串中的字符串,javascript,regex,Javascript,Regex,我有下面的字符串 Hello this is username (xxx) welcome to the portal 我需要将“username(xxx)”匹配并替换为一个用html标记封装的字符串。因此,它将如下所示 Hello this is <b>username (xxx) </b> welcome to the portal 您好这是用户名(xxx)欢迎访问门户 请注意,(xxx)是一个动态变量 如何使用正则表达式和javascript实现此功能?Tyr

我有下面的字符串

Hello this is username (xxx) welcome to the portal
我需要将“username(xxx)”匹配并替换为一个用html标记封装的字符串。因此,它将如下所示

Hello this is <b>username (xxx) </b> welcome to the portal
您好这是用户名(xxx)欢迎访问门户
请注意,(xxx)是一个动态变量

如何使用正则表达式和javascript实现此功能?

Tyr此:

var string=“您好,这是用户名(xxx)欢迎访问门户”
var newString=string.replace(/([a-z]+\s\(.+\)/g,'username(xxx)'

这是为您准备的JSFIDLE:

var str='您好,这是用户名(xxx),欢迎访问门户网站'
str=str.replace(/username\(.+)\)/,“username($1)”)

捕获从字符串
用户名
到下一个
符号的所有字符

> "Hello this is username (xxx) welcome to the portal".replace(/(username[^\)]*\))/g, "<b>$1 </b>")
'Hello this is <b>username (xxx) </b> welcome to the portal'
“您好,这是用户名(xxx)欢迎访问门户”。替换(/(用户名[^\)]*\)/g,“$1”)
'您好,这是用户名(xxx)欢迎访问门户'

Google“javascript字符串regex replace”。您尝试过什么regex?几个示例输入和输出可能会有所帮助。试试这个
    var str = 'Hello this is username (xxx) welcome to the portal'
    str = str.replace(/username \((.+)\)/, "<b> username ($1) </b>")
> "Hello this is username (xxx) welcome to the portal".replace(/(username[^\)]*\))/g, "<b>$1 </b>")
'Hello this is <b>username (xxx) </b> welcome to the portal'