jQuery字符串使用split()方法在空格后拆分字符串

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

本文关键字:字符串 空格 拆分 方法 split jQuery      更新时间:2023-09-26

我的代码

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

这将给我一个值=myid 5

   var str1 = myid
   var str2 = 5

我想要这样的。。

如何使用拆分方法实现这一点

var str =$(this).attr('id');
var ret = str.split(" ");
var str1 = ret[0];
var str2 = ret[1];

使用内置函数: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);

​注意:即使字符串组之间有多个空格,这也有效

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

一线解决方案:

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

-或-

//<div id="mypost-5">
var postId = $(this).attr('id').split('mypost-')[1];

如果两者之间有一个或多个空格,

var str = $(this).attr('id');
var array = str.split(/'s+/g);
var str1 = array[0];
var str2 = array[1];