我有以下字符串
Hello this is username (xxx) welcome to the portal
我需要匹配并替换"用户名(xxx)"用一个用html标签封装的字符串。所以它看起来如下。
Hello this is <b>username (xxx) </b> welcome to the portal
请注意,(xxx)是一个动态变量。
如何使用正则表达式和javascript进行操作?
答案 0 :(得分:1)
Tyr this:
var string = "Hello this is username (xxx) welcome to the portal"
var newString = string.replace(/([a-z]+\s\(.+\))/g, '<b>username (xxx)</b>')
答案 1 :(得分:0)
以下是适合您的jsfiddle:http://jsfiddle.net/fj7fmooy/
var str = 'Hello this is username (xxx) welcome to the portal'
str = str.replace(/username \((.+)\)/, "<b> username ($1) </b>")
答案 2 :(得分:0)
将字符串username
中的所有字符捕获到下一个)
符号。
> "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'