Javascript how to split newline

后端 未结 12 1813
一整个雨季
一整个雨季 2020-11-28 06:48

I\'m using jquery, and I have a textarea. When I submit by my button I will alert each text separated by newline. How to split my text when there is a newline?



        
相关标签:
12条回答
  • 2020-11-28 07:30
    1. Move the var ks = $('#keywords').val().split("\n"); inside the event handler
    2. Use alert(ks[k]) instead of alert(k)

      (function($){
         $(document).ready(function(){
            $('#data').submit(function(e){
               e.preventDefault();
               var ks = $('#keywords').val().split("\n");
               alert(ks[0]);
               $.each(ks, function(k){
                  alert(ks[k]);
               });
            });
         });
      })(jQuery);
    

    Demo

    0 讨论(0)
  • 2020-11-28 07:32

    Try initializing the ks variable inside your submit function.

      (function($){
         $(document).ready(function(){
            $('#data').submit(function(e){
               var ks = $('#keywords').val().split("\n");
               e.preventDefault();
               alert(ks[0]);
               $.each(ks, function(k){
                  alert(k);
               });
            });
         });
      })(jQuery);
    
    0 讨论(0)
  • 2020-11-28 07:34

    It should be

    yadayada.val.split(/\n/)
    

    you're passing in a literal string to the split command, not a regex.

    0 讨论(0)
  • 2020-11-28 07:34

    Just

    var ks = $('#keywords').val().split(/\r\n|\n|\r/);

    will work perfectly.

    Be sure \r\n is placed at the leading of the RegExp string, cause it will be tried first.

    0 讨论(0)
  • 2020-11-28 07:35

    you don't need to pass any regular expression there. this works just fine..

     (function($) {
          $(document).ready(function() {
            $('#data').click(function(e) {
              e.preventDefault();
              $.each($("#keywords").val().split("\n"), function(e, element) {
                alert(element);
              });
            });
          });
        })(jQuery);
    
    0 讨论(0)
  • 2020-11-28 07:37

    The problem is that when you initialize ks, the value hasn't been set.

    You need to fetch the value when user submits the form. So you need to initialize the ks inside the callback function

    (function($){
       $(document).ready(function(){
          $('#data').submit(function(e){
          //Here it will fetch the value of #keywords
             var ks = $('#keywords').val().split("\n");
             ...
          });
       });
    })(jQuery);
    
    0 讨论(0)
提交回复
热议问题