jQuery string split the string after the space using split() method

前端 未结 3 1065
眼角桃花
眼角桃花 2021-02-07 13:27

my code

  var str =$(this).attr(\'id\');

this will give me value == myid 5

   var str1 = myid
   var str2 = 5         


        
相关标签:
3条回答
  • 2021-02-07 13:41

    One line solution:

    //<div id="mypost-5">
    var postId = this.id.split('mypost-')[1] ); //better solution than the below one!
    

    -OR-

    //<div id="mypost-5">
    var postId = $(this).attr('id').split('mypost-')[1];
    
    0 讨论(0)
  • 2021-02-07 13:43

    Use in-built function: split()

    var source = 'myid 5';
    
    //reduce multiple places to single space and then split
    var splittedSource = source.replace(/\s{2,}/g, ' ').split(' ');
    
    console.log(splittedSource);
    

    ​ Note: this works even there is multiple spaces between the string groups

    Fiddle: http://jsfiddle.net/QNSyr/6/

    0 讨论(0)
  • 2021-02-07 13:47
    var str =$(this).attr('id');
    var ret = str.split(" ");
    var str1 = ret[0];
    var str2 = ret[1];
    
    0 讨论(0)
提交回复
热议问题