简体   繁体   English

需要正则表达式在*粗体之间制作文本

[英]Need regular expression for making text between * bold

I'm trying to bold the text between * , like *bold* I'm trying regular expressions in JavaScript but I don't know why its not working. 我试图在*之间加粗文本,像*bold*我在JavaScript中尝试正则表达式,但我不知道为什么它不起作用。

var bold = /\*(.*?)\*/gim;
var replacedText = replacedText.replace(bold, function($0,$1){
    return $1?$0:'<b>' + $0 + '</b>';
});

Thank you guys here is final Answer 谢谢你们这里是最后的答案

Edited 编辑

var bold = /\*(.*?)\*/gim;
var replacedText = replacedText.replace(bold, function($0,$1){
    return $1 ? ('<b>' + $1 + '</b>') : $0;
});

The regex is OK, but your logic is not: 正则表达式没问题,但你的逻辑不是:

var replacedText = replacedText.replace(bold, function($0,$1){
    return $1 ? ('<b>' + $1 + '</b>') : $0;
});

The condition was inverted, and in any case you should be using $1 when replacing instead of $0 (the latter includes the asterisks). 条件被颠倒了,在任何情况下,你应该使用$1代替$0 (后者包括星号)。

Something like: 就像是:

function makeBold(id) {

  var re = /(\*)([^*]*)(\*)/g;

  var el = document.getElementById(id);
  el.innerHTML = el.innerHTML.replace(re, '<b>$2</b>');
}

should get you started. 应该让你开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM