0

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

1
  • Missing a necessary tag: javascript I presume? -- EDIT: Thank you. Commented May 4, 2011 at 18:16

4 Answers 4

2

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Agreed, I'd use .join(',') though... and !~indexOf perhaps
Until you have Smith, John <[email protected]> in your contact list.
@Brad: Of course. I was basing my answer on the example he provided. I can't code for every possible case if I don't know every possible case.
0

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);

OUTPUT

Peter Johnson <[email protected]>, John Michaels <[email protected]>

Comments

0

Try this one:

[^,]+? <[email protected]>,?

This will do what you want, tailor it to your precise needs.

See here for more information.

Comments

0

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;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.