Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

my code

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

this will give me value == myid 5

   var str1 = myid
   var str2 = 5

i want something like this ..

how to achieve this using split method

like image 763
Hussy Avatar asked Sep 05 '12 10:09

Hussy


People also ask

How do you split a string after space?

To split a string with space as delimiter in Java, call split() method on the string object, with space " " passed as argument to the split() method. The method returns a String Array with the splits as elements in the array.

How do I split a string into multiple spaces?

To split a string by multiple spaces, call the split() method, passing it a regular expression, e.g. str. trim(). split(/\s+/) . The regular expression will split the string on one or more spaces and return an array containing the substrings.

How do I split a space in JavaScript?

To split a string keeping the whitespace, call the split() method passing it the following regular expression - /(\s+)/ . The regular expression uses a capturing group to preserve the whitespace when splitting the string.


2 Answers

var str =$(this).attr('id');
var ret = str.split(" ");
var str1 = ret[0];
var str2 = ret[1];
like image 186
xdazz Avatar answered Oct 27 '22 05:10

xdazz


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/

like image 31
Dhanasekar Avatar answered Oct 27 '22 06:10

Dhanasekar