2015-07-02 156 views
1

如果我有类似的文字:粗体字*

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

我需要大胆这个文字和文本。

我需要转换为<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轮或更多的比赛。它不是做这个:

我需要大胆这个文本和文字和这个文本和文本

+0

对不起,看着太多的问题,虽然行被拆分/爆炸,将删除,以免误导 – atmd

+1

'“我需要加粗*这个*文本和*那*文本。 [^ *] +)\ * /克, “$ 1”)' – epascarello

回答

5

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

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

@frosty你它重新分配给'str'? – Kasramvd

+1

是的,我忘了。 nvm,它运作良好! – frosty

+0

@Kasra你在这里不需要'?'。 –

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);
<pre id=r></pre>

这样可以节省你任何奇怪的转义规则,并可以很容易地返回前检查状态下能够防止不平衡标签。

+0

你不应该设置innerHTML吗? – epascarello

+0

@epascarello我不确定哪个更适合演示(pre + textContent为您提供实际输出)。 – ssube