首页 文章

Javascript替换参考匹配组?

提问于
浏览
179

我有一个字符串,例如 hello _there_ . 我想使用 JavaScript 分别用 <div></div> 替换两个下划线 . 输出(因此)看起来像 hello <div>there</div> . 该字符串可能包含多对下划线 .

我正在寻找的是一种方法 either 在每个匹配上运行一个函数,Ruby的方式:

"hello _there_".gsub(/_.*?_/) { |m| "<div>" + m[1..-2] + "</div>" }

Or 能够引用匹配的组,再次以红宝石的方式完成:

"hello _there_".gsub(/_(.*?)_/, "<div>\\1</div>")

任何想法或建议?

2 回答

  • 25
    "hello _there_".replace(/_(.*?)_/, function(a, b){
        return '<div>' + b + '</div>';
    })
    

    哦,或者你也可以:

    "hello _there_".replace(/_(.*?)_/, "<div>$1</div>")
    
  • 301

    您可以使用 replace 而不是 gsub .

    "hello _there_".replace(/_(.*?)_/g, "<div>\$1</div>")
    

相关问题