15

我的代码

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

这会给我价值== myid 5

   var str1 = myid
   var str2 = 5

我想要这样的东西..

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

4

3 回答 3

51
var str =$(this).attr('id');
var ret = str.split(" ");
var str1 = ret[0];
var str2 = ret[1];
于 2012-09-05T10:07:44.460 回答
2

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

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

小提琴:http: //jsfiddle.net/QNSyr/6/

于 2012-09-05T11:18:51.053 回答
1

一线解决方案:

//<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];
于 2016-07-27T10:16:12.257 回答