簡體   English   中英

js中基於正則表達式的替換

[英]Regex based replace in js

實際上我想要替換一個字符串,除非它是一個圓括號。

例如:

JAVA is a nice language. (JAVA) has lots of features. JAVA is portable. (JAVA) even comes in 64 bit.

現在,如果我用C替換JAVA:

那么期望的輸出是:

C is a nice language. (JAVA) has lots of features. C is portable. (JAVA) even comes in 64 bit. 

甚至java都可以作為子字符串來

 XJAVAX is a nice language. (XJAVAX) has lots of features. JAVA is portable. (JAVA) even comes in 64 bit.

現在,如果我用C替換JAVA:

然后預期輸出:

XCX is a nice language. (XJAVAX) has lots of features. C is portable. (JAVA) even comes in 64 bit.

由於JavaScript沒有后視,最簡單的方法可能是改變:

str = str.replace(/\(JAVA\)|JAVA/g, function(m) {
    return m === "(JAVA)" ? m : "C";
    // Or
    // return m.length === 6 ? m : "C";
});

除此之外,您還可以嘗試模擬look-behind ,這在某些方面是可能的,但是很混亂。

暫無
暫無

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

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