2015-07-02 155 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