2011-02-03 34 views
24

如何替換jQuery中的任何字符串?用jQuery代替HTML頁面中的文本

比方說,我有一個字符串"-9o0-9909",我想用另一個字符串替換它。

+1

可能的重複[如何用另一個HTML塊替換HTML塊使用jQuery](http://stackoverflow.com/questions/2734174/how-to-replace-a-block-of-html-with -otherother-block-of-html-using-jquery)在提出問題之前,最好查看系統在輸入問題標題時所做的自動化建議 – 2011-02-03 12:49:40

+0

請問您爲什麼認爲jquery是要走的路 - 迄今爲止的答案可能偏離正軌。 – Xhalent 2011-02-03 13:02:12

+0

我可以在c#頁面,javascript和數據庫和html頁面中更改文本,但是我想如果可以在頁面加載後使用jQuery來實現該功能。我試圖保存一段時間,並學習新的東西:) – Developer 2011-02-03 16:50:25

回答

53

您可以使用下面的頁面體內替換單詞的第一個匹配:

var replaced = $("body").html().replace('-9o0-9909','The new string'); 
$("body").html(replaced); 

如果你想更換的所有出現字,您需要使用正則表達式並將其聲明爲全局/g

var replaced = $("body").html().replace(/-1o9-2202/g,'The ALL new string'); 
$("body").html(replaced); 

如果你想要一個襯墊:

$("body").html($("body").html().replace(/12345-6789/g,'<b>abcde-fghi</b>')); 

你基本上把所有的頁面轉換成字符串變量的<body>標籤內的HTML,使用replace()以查找和更改找到的第一次出現帶有新字符串的字符串。或者,如果您想查找並替換所有出現的字符串,請爲該混合引入一點正則表達式。

See a demo here - 看看左上角的HTML,看到原始文本,下面的jQuery和輸出到右下角。

13

...我有一個字符串「-9o0-9909」,我想用另一個字符串替換它。

下面的代碼將做到這一點。

var str = '-9o0-9909'; 

str = 'new string'; 

笑話不談,替換文本節點是不平凡的JavaScript。

我寫了一篇關於此的文章:Replacing text with JavaScript

+5

不知道爲什麼你的答案不被接受。 – 2012-08-06 09:45:06

+1

鏈接上的代碼處理*幾乎*所有情況。對於我來說,它在集合中'
`中出現(`c​​hild`爲`null`),並且它也會在splitText中崩潰,並且「split offset超出文本節點長度」。另外,「畫布」被拼寫爲「cavas」。儘管如此,+1。 – bishop 2014-09-20 19:01:25

+0

@bishop謝謝,我絕對需要更新那篇文章。 – alex 2014-09-22 00:28:55

1
var replaced = $("body").html().replace(/-1o9-2202/g,'The ALL new string'); 
$("body").html(replaced); 

變量:

var replaced = $("body").html().replace(new RegExp("-1o9-2202", "igm"),'The ALL new string'); 
$("body").html(replaced); 
2

退房Padolsey's article on DOM find and replace,以及the library to implement the described algorithm

在此示例中使用,我代替所有文字<div id="content">,看起來像一個tel:方案鏈接美國的電話號碼裏面:

findAndReplaceDOMText(document.getElementById('content'), { 
    find:/\b(\d\d\d-\d\d\d-\d\d\d\d)\b/g, 
    replace:function (portion) { 
     var a = document.createElement('a'); 
     a.className = 'telephone'; 
     a.href = 'tel:' + portion.text.replace(/\D/g, ''); 
     a.textContent = portion.text; 
     return a; 
    } 
}); 
5

的HTML替代的想法是好的,但如果做的文檔。正文,頁面將閃爍,廣告將消失。

我的解決辦法:
$("*:contains('purrfect')").each(function() { var replaced = $(this).html().replace(/purrfect/g, "purrfect"); $(this).html(replaced); });

24

如在此線程提到別人,替換整個身體HTML是一個糟糕的主意,因爲它重新插入整個DOM,並可能會破壞被作用於這些元素,任何其他的JavaScript。

相反,使用jQuery filter更換隻是你的頁面上的文本,而不是DOM元素本身:

$('body :not(script)').contents().filter(function() { 
    return this.nodeType === 3; 
    }).replaceWith(function() { 
     return this.nodeValue.replace('-9o0-9909','The new string'); 
    }); 

this.nodeType爲節點,我們正在尋找替換的內容的類型。節點類型3是文本。 See the full list here