只给出了电子邮件地址,我试图从字符串中删除电子邮件,相应人员的姓名和以下逗号(如果存在),无论电子邮件出现在字符串中的哪个位置。
var str = 'Peter Johnson <aa156@ss.edu>, Bob Cooper-Junior <aa1233@ss.edu>, John Michaels <qq@zzz.edu>';
所以,如果我要删除'aa1233@ss.edu'
,我最终会:
var str = 'Peter Johnson <aa156@ss.edu>, John Michaels <qq@zzz.edu>';
由于
答案 0 :(得分:2)
为什么不使用','作为分隔符来拆分字符串并找到哪个索引包含'aa1233@ss.edu'并重建没有该索引的字符串? See Working Example Here
var newString = '';
var oldString = 'Peter Johnson <aa156@ss.edu>, Bob Cooper-Junior <aa1233@ss.edu>, John Michaels <qq@zzz.edu>';
var arrEmails = oldString.split(",");
for (i=0;i<arrEmails.length;i++){
if (arrEmails[i].indexOf('aa1233@ss.edu') == -1){
if (newString.length > 0) newString += ',' + arrEmails[i];
else newString = arrEmails[i];
}
}
alert(newString);
答案 1 :(得分:0)
试试这个:
var toRemove = "aa1233@ss.edu";
var str = 'Peter Johnson <aa156@ss.edu>, Bob Cooper-Junior <aa1233@ss.edu>, John Michaels <qq@zzz.edu>';
var arr = str.split(",");
for (var i=0; i<arr.length; i++) {
if (arr[i].indexOf(toRemove) != -1) {
str = str.replace(arr[i] + ",", "");
break;
}
}
// output it
alert(str);
Peter Johnson <aa156@ss.edu>, John Michaels <qq@zzz.edu>
答案 2 :(得分:0)
答案 3 :(得分:0)
通常,不使用正则表达式是更清晰的解决方案:
var people = str.split(", ");
for (var i = 0, l = people.length; i < l; i++) {
if (people[i].indexOf(email) != -1) {
people.splice(i, 1);
str = people.join(", ");
break;
}
}