我有一个看起来像这样的字符串:
nxtisFixed IncomenxtisForexnxtisMoney Marketsnxtis
我想在它上面使用正则表达式,所以它看起来像这样:
Fixed Income, Forex, Money Markets
我试过这个:
var withoutnxtis = data.replace(/^nxtis/, "");
withoutnxtis = data.replace(/nxtis$/, "");
但它没有用。任何人都可以帮助我吗?
答案 0 :(得分:1)
var data = "nxtisFixed IncomenxtisForexnxtisMoney Marketsnxtis";
var withoutnxtis = data.replace(/nxtis/gi, ", ").replace(/^,\s*|,\s*$/g, '');
console.log(withoutnxtis);
解释:
/ nxtis / gi
nxtis 匹配字符nxtis字面上 (不区分大小写)g修饰符:全局。所有比赛(首场比赛不返回)
i修饰符:不敏感。不区分大小写的匹配(忽略大小写的情况) [A-ZA-Z])<强> / ^,\ S * |,\ S * /克强>
第一选择:^,\ s *
^ 断言字符串开头的位置 ,字符,匹配 \ s * 匹配任何空格字符 [\ r \ n \ t \ f]
量词:* 在零和无限次之间,尽可能多次,根据需要回馈[贪心]第二种选择:,\ s *
,字符,匹配 \ s * 匹配任何空格字符 [\ r \ n \ t \ f]
量词:* 在零和无限次之间,尽可能多次,根据需要回馈[贪心]
g修饰符:全局。所有比赛(首场比赛时不返回)
答案 1 :(得分: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
&#13;
另一种方法是在替换前用逗号和空格删除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;
&#13;
答案 2 :(得分:1)
我找到了解决方案。这是它应该是什么( data 是输入字符串):
var re = /((?:nxtis)+)/g;
return data.replace(re, ', ')
.replace(/^(\s*,\s*)/,'')
.replace(/(\s*,\s*)$/,'');