【问题标题】:Regex bold characters using *使用 * 的正则表达式粗体字符
【发布时间】:2015-07-02 16:41:24
【问题描述】:

如果我有这样的文字:

I need to bold *this* text and *that* text.

我需要将this文本和that文本加粗。

我需要同时转换为<b>this</b><b>that</b>

var str = $('textarea#commentfield').val();
var getBold = str.match(/\*.+\*/g);
if(getBold!=null){
  getBold = getBold.toString().replace(/\*/g,"");
}
str = str.replace(/\*[^*]+?\*/g, "<b>"+getBold+"<\/b>");

这不是我想要的 2 场或更多场比赛。它正在这样做:

我需要加粗这个文本和那个文本和这个文本和那个文本。

【问题讨论】:

  • 不好意思,看的问题太多了,虽然线路被拆分/爆炸了,为了不误导会删掉
  • "I need to bold *this* text and *that* text.".replace(/\*([^*]+)\*/g,"&lt;b&gt;$1&lt;/b&gt;")

标签: javascript regex


【解决方案1】:

您可以只使用捕获组和组参考号:

str =str.replace(/\*([^*]+)\*/g, "<b>$1<\/b>");

【讨论】:

  • @frosty 你把它重新分配给str了吗?
  • @Kasra 你这里不需要?
  • @AvinashRaj 为什么?它应该是非贪婪的!
  • 不贪心?那你为什么使用否定的 char 类?是的,非贪婪仅在您使用 .* 时适用,因为 . 将匹配任何字符,包括 *[^*] 不会。
  • @AvinashRaj 啊,是的,非常感谢!我一直很关心这一点,但在这种情况下,正如 OP 所说的那样,我已经错过了!
【解决方案2】:

在替换每个星号时只需使用闭包来跟踪标签状态:

function embolden(str) {
  var open = false;
  var ret = str.replace(/\*/g, function() {
    if (open) {
      open = false;
      return '</b>';
    } else {
      open = true;
      return '<b>';
    }
  });
  if (open) {
    ret += '</b>';
  }
  return ret;
}


var input = 'I need to bold *this* text and *that* text.';
document.getElementById('r').innerHTML = embolden(input);
&lt;pre id=r&gt;&lt;/pre&gt;

这为您节省了任何奇怪的转义规则,并且可以通过在返回之前检查状态来轻松避免不平衡的标签。

【讨论】:

  • 你不应该设置innerHTML吗?
  • @epascarello 我不确定哪个更适合演示(pre + textContent 为您提供实际输出)。
【解决方案3】:

。 * bold * 和 \n break

function(sting){
    let  str = sting.replace(/\*([^*]+)\*/g, "<b>$1<\/b>");
    return str.replace(/\n/g, "<br />");
}

【讨论】:

    猜你喜欢
    • 2017-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    相关资源
    最近更新 更多