Reputation: 1
Given only the email address, I'm trying to remove the email, corresponding person's name and the following comma (if exist) from the string regardless where in the string the email appears.
var str = 'Peter Johnson <[email protected]>, Bob Cooper-Junior <[email protected]>, John Michaels <[email protected]>';
so if I want to remove '[email protected]'
I would end-up with:
var str = 'Peter Johnson <[email protected]>, John Michaels <[email protected]>';
Thanks
Upvotes: 0
Views: 71
Reputation: 6866
Why not split the string using ',' as your delimiter and find which index contains '[email protected]' and rebuild the string without that index? See Working Example Here
var newString = '';
var oldString = 'Peter Johnson <[email protected]>, Bob Cooper-Junior <[email protected]>, John Michaels <[email protected]>';
var arrEmails = oldString.split(",");
for (i=0;i<arrEmails.length;i++){
if (arrEmails[i].indexOf('[email protected]') == -1){
if (newString.length > 0) newString += ',' + arrEmails[i];
else newString = arrEmails[i];
}
}
alert(newString);
Upvotes: 2
Reputation: 140182
More than often, not using regular expressions is the cleaner solution:
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;
}
}
Upvotes: 0
Reputation: 27831
Try this one:
[^,]+? <[email protected]>,?
This will do what you want, tailor it to your precise needs.
See here for more information.
Upvotes: 0
Reputation: 786329
Try this:
var toRemove = "[email protected]";
var str = 'Peter Johnson <[email protected]>, Bob Cooper-Junior <[email protected]>, John Michaels <[email protected]>';
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 <[email protected]>, John Michaels <[email protected]>
Upvotes: 0