簡體   English   中英

Javascript-用另一個正則表達式替換正則表達式

[英]Javascript - Replace a Regex with another Regex

我的網頁中有一個字符串(例如0511 51 51 86 86)(可能多次出現),並且我想使用正則表達式將其替換為另一個字符串(在這種情況下為0511 51 51 86 86 *)。

我嘗試使用replace()函數來查找所有出現的事件並進行替換。 使用字符串作為replace()中的參數可以很好地工作。 但是如果我使用Regex則不會。

我已經試過了:

$("body").html($("body").html().replace(/0\d{3} \d{2} \d{2} \d{2} \d{2}/g, /0\d{3} \d{2} \d{2} \d{2} \d{2}\*/g));

我想要的是,用正則表達式替換所有這些:0511 51 51 86 86 *:0511 51 51 86 86 *。

在替換字符串中,可以使用$&包含所有替換的文本。 所以:

replacement = original.replace(/\d{4}(?: \d{2}){4}/g, "$&*");

例:

 const original = "blah blah blah 0511 51 51 86 86 blah blah blah"; const replacement = original.replace(/\\d{4}(?: \\d{2}){4}/g, "$&*"); console.log(replacement); 

您問過:

這合法嗎: $("body").html($("body").html().replace(/\\d{4}(?: \\d{2}){4}/g, "$&*")); 我使用$("body").html()因為我沒有特定的字符串。 整個網頁內容都在那里。

是的,但這是一個非常糟糕的主意。 它會完全撕毀該頁面(刪除所有可能已附加的事件處理程序或元素數據),並將其替換為新頁面,這是重新解析HTML的結果。

而是使用簡單的遞歸函數來更新頁面的文本節點:

const rex = /\d{4}(?: \d{2}){4}/g;

function doReplacement(element) {
    for (let child = element.firstChild; child; child = child.nextSibling) {
        if (child.nodeType === 3) {        // A text node
            child.nodeValue = child.nodeValue.replace(rex, "$&*");
        } else if (child.nodeType === 1) { // An element
            doReplacement(child);
        }
    }
}

doReplacement(document.body);

現場示例:

 const rex = /\\d{4}(?: \\d{2}){4}/g; function doReplacement(element) { for (let child = element.firstChild; child; child = child.nextSibling) { if (child.nodeType === 3) { // A text node child.nodeValue = child.nodeValue.replace(rex, "$&*"); } else if (child.nodeType === 1) { // An element doReplacement(child); } } } doReplacement(document.body); 
 blah blah blah 0511 51 51 86 86 blah blah blah <p> blah blah blah 0511 50 52 68 68 blah blah blah <span> blah blah blah 0511 49 27 67 24 blah blah blah </span> </p> <div> blah blah blah 0511 51 51 86 86 blah blah blah <p> blah blah blah 0511 50 52 68 68 blah blah blah <span> blah blah blah 0511 49 27 67 24 blah blah blah </span> </p> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM