skip to Main Content

here i have two input field as like

$(document).ready(function() {
   $("#business_name").keyup(function() {
      var Text = $(this).val();
      Text = Text.toLowerCase();
      Text = Text.replace(/[^a-zA-Z0-9]+/g,'-');
      $("#business_url").val(Text);        
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" id="business_name" name="business_name" placeholder="Business Name" />
<br><br>
<input type="text" id="business_url" name="business_url" placeholder="Business URL" />

now I want if someone wrote : My Business Name on first input field then 2nd field it will be write mybusiness thats it but now it showed my-business-name i dont want this (I need only two word if it will take longer name then it only shows first two word thats it )

2

Answers


  1. To get only the first two words you can split() the string in to an array by spaces and then use slice() to get the first two elements of the resulting array. Then you can join it back together before displaying in the input.

    Also note I added trim() and a regex to replace multiple whitespace with a single one, otherwise it would affect how split() builds the array and could end up missing words.

    jQuery($ => {
      $("#business_name").on('input', e => {
        var text = $(e.target).val().trim().replace(/s+/, ' ').toLowerCase().split(' ').slice(0, 2).join('');
        $("#business_url").val(text);
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="text" id="business_name" name="business_name" placeholder="Business Name" /><br /><br />
    <input type="text" id="business_url" name="business_url" placeholder="Business URL" />
    Login or Signup to reply.
  2. After replacing certain characters with ‘ ‘ count the number of ‘ ‘ in the string. If the count is 2 stop replacing or you can return from the function.

    Look at the modified code below:

    $(document).ready(function() {
       var count = 0;
       $("#business_name").keyup(function() {
          var Text = $(this).val();
          Text = Text.toLowerCase();
          Text = Text.replace(/[^a-zA-Z0-9]+/g,' ');
          count = (Text.split("-")).length - 1;
          if (count == 2) {
              return;
          }
          $("#business_url").val(Text);        
        });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search