2011-12-21 30 views
2

我試圖在普通的舊html中創建一種'模板',然後可以通過其他javascript函數插入元素。JavaScript替換 - 不使用html的字符串

所以,我有

var string = "<div id='<@nameInsert>' style='padding: 2px;'>here's some text and stuff</div>"; 

而且在功能我試圖取代< @nameInsert>與我使用的名稱...

string.replace("/<@nameInsert>", "525"); 

但是,它不起作用。某種逃避的東西,錯誤的想法,或者是什麼?

+0

確保它不工作? http://jsfiddle.net/alfabravoteam/xLdQT/ – Alfabravo 2011-12-21 14:48:30

回答

2

,如果你想使用正則表達式

string.replace(/<@nameInsert>/, "525"); 

但在你的情況,你並不真的需要正則表達式不使用引號。只需使用一個字符串:

string.replace("<@nameInsert>", "525"); 
+0

好神人 - 直入,完成。那麼如何工作呢? – waxical 2011-12-21 14:34:47

0

對我來說工作確定這個樣子,

string=string.replace("<@nameInsert>", "525"); 

這裏有一個例子

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html> 
<head> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 
    <script language="javascript"> 

    function test(){ 
    var string = "<div id='<@nameInsert>' style='padding: 2px;'>here's some text and stuff</div>"; 
    string=string.replace("<@nameInsert>", "525"); 
    alert(string); 
    } 

</script> 
</head> 
<body> 
    <input type="button" value="test" name="test" onclick="test()"> 

</body> 
</html> 
3

它不工作,因爲你正在試圖取代在另一個字符串中不存在的字符串。

我認爲你正在混合兩種不同的替換方式。您可以替換使用字符串:

string.replace("<@nameInsert>", "525"); 

,您可以使用正則表達式替換:

string.replace(/<@nameInsert>/, "525"); 

與斜線的部分是一個正則表達式的文本,這給了相同的結果:

string.replace(new RegExp("<@nameInsert>"), "525"); 

您可能更喜歡正則表達式,因爲您可以指定全局標誌,這將使其替換每個發生的事件,而不僅僅是第一個:

string.replace(/<@nameInsert>/g, "525"); 
+0

謝謝Guffa。一個問題似乎是,這不適用於標籤內的內容 - 例如查找和替換「文本」 - 不起作用? – waxical 2011-12-21 15:25:21

+1

@waxical:'replace'方法不關心字符串恰好包含HTML代碼;標籤內的文字處理方式不同。請注意,'replace'方法不會更改字符串,它會返回新的字符串。你必須使用返回值:'string = string.replace(/ text/g,'woohaa!');'。 – Guffa 2011-12-21 15:56:01

+0

謝謝Guffa。我最終也發現了這一點。 – waxical 2011-12-21 16:37:07

0

如果您使用斜槓(/)或引號(「),因爲您只有一個字符串來替換..沒關係,但只是確保您瞭解替換方法..它不會取代現有的字符串,而是返回它的一個修改後的副本.. 所以你可以做這樣的:

string = string.replace(/<@nameInsert>/, "525");