2016-02-02 64 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*)$/,''); 
相关问题