string replace underscore with open and close html tags

前端 未结 1 1596
隐瞒了意图╮
隐瞒了意图╮ 2021-01-22 08:07

I have a string with underscores around certain words that need replacement with an open and close html tags.

Heres w

相关标签:
1条回答
  • 2021-01-22 08:43

    You may use

    var str = "_Lorem Ipsum_ is simply dummy text";
    var t2 = str.replace(/_([^_]*)_/g, '<i>$1</i>');  
    console.log(t2);

    Details

    • _ - matches an underscore
    • ([^_]*) - Group 1: zero or more chars other than _
    • _ - an underscore.

    The replacement contains a replacement backreference, $1, that inserts the Group 1 value in between <i> and </i>.

    See the regex demo.

    0 讨论(0)
提交回复
热议问题