2011-12-28 66 views
-2

如何替換任何給定的網頁客戶端上的每一個單詞與var cms是什麼? 不需要什麼js依賴關係,或者鏈接是否中斷。替換全部文本

+0

你需要更多的敘述你的問題。 – Sang 2011-12-28 06:20:01

+0

因此,如果'cms'是「測試」,並且頁面有'您好,那麼嗎? '',是您的預期結果'測試測試,測試測試測試?'或只是'測試'?請更新您的問題以包含詳細的示例。 – nnnnnn 2011-12-28 06:35:42

回答

2

嘗試:

 

function htmlreplace(a, b, element) {  
    if (!element) element = document.body;  
    var nodes = element.childNodes; 
    for (var n=0; n<nodes.length; n++) { 
     if (nodes[n].nodeType == Node.TEXT_NODE) { 
      var r = new RegExp(a, 'gi'); 
      nodes[n].textContent = nodes[n].textContent.replace(r, b); 
     } else { 
      htmlreplace(a, b, nodes[n]); 
     } 
    } 
} 

htmlreplace('a', 'r'); 

 
+0

如何讓每個**單個單詞匹配**?不只是一個字符串像「測試語句」會變成「xxx xxx xxx」 – jmoon 2011-12-28 06:25:23

+0

'nodes [n] .textContent = nodes [n] .textContent.replace(/ \ w +/g,b);' – 2011-12-28 06:37:21

1

可能你正在談論這一點:

var myOldString = "Hello username! I hope you enjoy your stay username."; 
var myNewString = myOldString.replace(/username/g, "pranay"); 
+0

@jmoon - 你可以嘗試整個頁面內容的重新空間功能,就​​像我應用在字符串........ – 2011-12-28 06:25:50

+0

我需要它匹配*一切*,而不是一個字符串。像document.body.replace(「new word here」); – jmoon 2011-12-28 06:28:24