Javascript jQuery字符串使用split()方法分割空格后的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12278999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:35:35  来源:igfitidea点击:

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

javascriptjquery

提问by Hussy

my code

我的代码

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

this will give me value == myid 5

这会给我价值 == myid 5

   var str1 = myid
   var str2 = 5

i want something like this ..

我想要这样的东西..

how to achieve this using split method

如何使用拆分方法实现此目的

回答by xdazz

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

回答by Dhanasekar

Use in-built function: split()

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

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

回答by Reza Mamun

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];