jQuery字符串使用split()方法在空格后拆分字符串
我的代码
var str =$(this).attr('id');
这会给我价值== myid 5
var str1 = myid var str2 = 5
我想要这样的东西..
如何使用split方法实现此目的
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);
注意:即使字符串组之间有多个空格也可以
小提琴: http : //jsfiddle.net/QNSyr/6/
一线解决方案:
// var postId = this.id.split('mypost-')[1] ); //better solution than the below one!
-要么-
// var postId = $(this).attr('id').split('mypost-')[1];