2013-10-07 27 views
1
sampleText='6501-*-5-[*]' 

預期輸出Javascript成爲正則表達式

result='6501-%-5-[*]' 

我不得不更換*由%和離開[*]原樣。兩者可能有多重發生。我們如何在JavaScript中做到這一點。提前致謝。

+3

[?你嘗試過什麼(http://mattgemmell.com/2008/12/ 08/what-you-you-tried /) – heretolearn

回答

0

試試這個:

sampleText = sampleText.replace(/\*/g, function(match, offset){ 
    if(offset > 0) { 
     if(sampleText[offset - 1] == '[' && sampleText[offset + 1] == ']'){ 
      return match; 
     } 
    } 
    return '%'; 
}); 

小提琴:here

+1

完美..工作就像一個魅力.. – Joe

+0

一件事SampleText = * r [*] d [A * BACD] ResultText =%r * da * bacd,即方括號內的任何內容都將被忽略......我該如何做到這一點?對此的任何方向...? – Joe

+0

@ user714537這很簡單,但我把它留給你作爲練習:) –

0

您可以使用String.replace()方法。 Doc here

例如:

text = '6501-*-5-[*]'; 
text = text.replace('-*-','-%-'); 
console.log(text); // 6501-%-5-[*] 
+0

取代**第一** - * - 與 - % - 不是他的要求 –