2016-02-02 69 views
0

我有一個字符串,它看起來像這樣:正則表達式 - 從字符串中刪除一個字出現的所有

nxtisFixed IncomenxtisForexnxtisMoney Marketsnxtis 

我想它使用正則表達式,所以它看起來是這樣的:

Fixed Income, Forex, Money Markets 

我試過這個:

var withoutnxtis = data.replace(/^nxtis/, ""); 
withoutnxtis = data.replace(/nxtis$/, ""); 

但它沒有奏效。誰能幫我?

+0

刪除錨點,使用全局標誌'data.replace(/ nxtis /克, 「」);'' – Tushar

+0

s.split('nxtis ')' –

+0

修剪拆分過濾器加入。 'str.trim()。split('nxtis')。filter(e => e.trim())。join(',')' – Tushar

回答

1

var data = "nxtisFixed IncomenxtisForexnxtisMoney Marketsnxtis"; 
 
var withoutnxtis = data.replace(/nxtis/gi, ", ").replace(/^,\s*|,\s*$/g, ''); 
 
console.log(withoutnxtis);

闡釋:

/nxtis/GI

nxtis的字符匹配的nxtis字面上
(情況insens itive)g修飾詞:全球。所有匹配(不匹配第一個匹配)
我修飾符:不敏感。不區分大小寫匹配(忽略 [A-ZA-Z]的情況下)

/^,\ S * |,\ S * /克

第一備選:^,\ S *
在字符串
開始 ^斷言位置,字符字面上
\ S *匹配的匹配ÿ空白字符[\ r \ n \噸\ F]
量詞:*之間的零和無限次,多次地,用之於根據需要[貪婪]

第二替代方法: ,\ S *
匹配字符字面上
\ S *匹配任何空白字符[\ r \ n \噸\ F]
量詞:*零和無限次之間,儘可能多次,根據需要回饋[貪婪]
g修飾詞:全球。所有的比賽(不上的第一場比賽返回)

+1

與Wiktor的第一個答案不一樣。除了'我'國旗。 – Tushar

1

注意/^nxtis/只會在字符串的開始匹配nxtis/nxtis$/將匹配字符串結尾。你需要刪除字符串內的任何地方。

您可以使用下面的正則表達式基礎的解決方案:

var re = /nxtis/g;    // A regex to match all occurrences of nxtis 
 
var str = 'nxtisFixed IncomenxtisForexnxtisMoney Marketsnxtis '; 
 
var result = str.replace(re, ', ').replace(/^,\s*|,\s*$/g, ''); // Replace nxtis with ', ' 
 
document.body.innerHTML = result; // and remove initial and trailing commas with whitespace

另一種方法是用逗號和空格替換之前刪除nxtis

var re = /nxtis/g;    
 
var str = 'nxtisFixed IncomenxtisForexnxtisMoney Marketsnxtis '; 
 
var result = str.replace(/^\s*nxtis|nxtis\s*$/g, '').replace(re, ', '); 
 
document.body.innerHTML = result;

1

我找到了解決方案。下面是應該的(數據被輸入的字符串):

var re = /((?:nxtis)+)/g; 
return data.replace(re, ', ') 
      .replace(/^(\s*,\s*)/,'') 
      .replace(/(\s*,\s*)$/,''); 
相關問題