0

I have a mailer script in which I paste a list of email addresses in the input field (comma delimited) and based on those addresses the email subject is generated. Subject, in this case, should be the domain of the first recipient in the comma-delimited list.

The emails are pasted in the first input and heading is generated from domain address

So, basically, what should happen is that jQuery should take a list of comma-separated email addresses, capitalize the domain of the first email inputted, and put it into another input field.

It should be like this enter image description here

But I am stuck since I'm not sure how to use split with 2 params and plus capitalize that.

My code currently outputs stackoverflow.com, anothermail instead of Stackoverflow.com.

$(function () {
          var $src = $('#to'),
              $dst = $('#subject');
          $src.on('input', function () {
              $dst.val($src.val().split("@")[1]);
          });
      });

Thanks a lot for anyone's help.

Awesim
  • 99
  • 9
  • 1
    jQuery is a library for working with the DOM. It's not great with string manipulation. – VLAZ May 12 '21 at 17:04
  • So you're just looking to extract the first email address from a comma-separated list and capitalize the first letter? – kmoser May 12 '21 at 17:08
  • I am looking to extract the domain name of the first recipient and capitalizing that. – Awesim May 12 '21 at 17:08

2 Answers2

2

Have a look at this

$(function() {
 let $src = $('#to'),
    $dst = $('#subject');
  $src.on('input', function() {
    const to = $src.val();
    $dst.val(to.split(/[,;]/).map(email => {
      const domain = email.split('@')[1];
      return domain ? domain.charAt(0).toUpperCase() + domain.slice(1) : '';
    }).join(', '));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="to" />
<input type="text" id="subject" />
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

Split the string on commas (followed by optional spaces) to separate the email addresses and take the first element (index 0): $src.val().split( /,\s*/ )[0]. Then split that email address on @, and take the 2nd half (index 1): split(/@/)[1].

All together:

// Extract the first domain name from the list of emails:
let s = $src.val().split( /,\s*/ )[0].split(/@/)[1]

// Convert first letter to uppercase:
s = s[0].toUpperCase() + s.substring(1);

Applied to your code:

$(function () {
  var $src = $('#to'),
  $dst = $('#subject');
  $src.on('input', function () {
    let s = $src.val().split( /,\s*/ )[0].split(/@/)[1];
    $dst.val( s[0].toUpperCase() + s.substring(1) );
  });
});

For alternate ways of capitalizing the string, see How do I make the first letter of a string uppercase in JavaScript?

kmoser
  • 8,780
  • 3
  • 24
  • 40