开发者

how to add markup to text using JavaScript regex

I need to add markup to some text using JavaScript regular expressions. In Python I could do this with:

>>> imp开发者_如何学Cort re
>>> re.sub('(banana|apple)', r'<b>\1</b>', 'I have 1 banana and 2 apples!')
'I have 1 <b>banana</b> and 2 <b>apple</b>s!'

What is the equivalent in JavaScript? string.replace(regex, newstring) seems to only take a raw string for replacing.


In the new string, you can reference capture groups via the tokens $1, $2, etc. A lot of the high-level reference sites (like w3schools) fail to document that. It's in the spec, of course, or more accessibly discussed on MDC.

So taking your example:

"I have 1 banana and 2 apples!".replace(/(banana|apple)/gi, "<b>$1</b>");

(Of course, the "s" in "apples" won't be inside the tag...) I used the 'i' flag there assuming you want to process "Banana" and "Apple" as well as "banana" and "apple".


You can use String.replace() for this and use $n to reference captured groups from the regular expression:

var in = 'I have 1 banana and 2 apples!';
var out = in.replace(/(banana|apple)/g, "<b>$1</b>");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜