2011-05-05 30 views
0

我需要一個正則表達式來替換Var = xxxx。正則表達式在JavaScript中替換Var = xxxx

前:index.php文件選項= XYZ

location.replace("--regex to replace option=xyz--","--something--") 

好吧,我發現所有你的答案更好的解決方案。下面是完整的解決方案:

window.location.href.replace(/option=.+&/,'some text') 
+0

你不需要一個正則表達式。 'var result ='Var = xxxx'.replace('Var = xxxx','something');' – BoltClock 2011-05-05 23:57:07

+0

xxxx不是靜態的 – ShirazITCo 2011-05-05 23:59:09

+0

@BoltClock實際上是一個正則表達式。 @ShirazITCo如果你有想要替換的變量,那麼就把它作爲'replace()'的參數。 – bdares 2011-05-06 00:02:06

回答

1
window.location.href = window.location.href.replace(/var\=xxxx/, "somevalue"); 

當然,你會希望把正確的正則表達式要替換鍵/值。

+0

從什麼時候開始'='需要轉義? – BoltClock 2011-05-06 00:01:01

+0

在這種情況下並非如此,但'='用於零長度斷言,例如'(?= ...)'。有關係嗎? :) – Ryan 2011-05-06 00:01:56

1

比方說你的字符串看起來是這樣的:

ticketsSold=30 
for(i=0; i<10; i++) 
    ticketsSold = ticketsSold+1; 

alert("total ticketsSold = " + ticketsSold); 

讓該行存放在一個變量:

var s="ticketsSold=30\nfor(i=0; i<10; i++)\nticketsSold = ticketsSold+1;\nalert("total ticketsSold = " + ticketsSold);" 

馬上試試他的

alert(s.replace(/[a-zA-z0-9_]+=.+/,'nothing')); 

你的輸出就會

nothing 
for(i=0; i<10; i++) 
ticketsSold=ticketsSold+1; 
alert('total ticketsSold='+ticketsSold); 

我們用「無」取代了ticketsSold = 30。