admin管理员组

文章数量:1287513

I am using jQuery

I have got below in my string

str = "Michael,Singh,34534DFSD3453DS"

Now I want my result in three variables.

str1 = "Michael"
str2 = "Singh"
str3 = "34534DFSD3453DS"

Please suggest!

Thanks

I am using jQuery

I have got below in my string

str = "Michael,Singh,34534DFSD3453DS"

Now I want my result in three variables.

str1 = "Michael"
str2 = "Singh"
str3 = "34534DFSD3453DS"

Please suggest!

Thanks

Share Improve this question edited Dec 16, 2010 at 9:11 Yi Jiang 50.2k16 gold badges138 silver badges136 bronze badges asked Dec 16, 2010 at 9:08 Manoj SinghManoj Singh 7,70734 gold badges122 silver badges201 bronze badges 1
  • 1 No need for "Please suggest!" and the like. If people are reading your question, their reason for doing so is to reply and help you. – T.J. Crowder Commented Dec 16, 2010 at 9:12
Add a ment  | 

5 Answers 5

Reset to default 5

var strs = str.split(',') is your best bit. This will create an array for you so

strs[0] = "Michael"
strs[1] = "Singh"
strs[2] = "34534DFSD3453DS"

However, it is possible to get exactly what you want by adding new items to the window object. For this I use the $.each method of jQuery. It's not necessary (you can just use a for) but I just think it's pretty :). I don't remend it, but it does show how you can create new variables 'on the fly'.

var str = "Michael,Singh,34534DFSD3453DS";

$.each(str.split(','), function(i,item){
   window['str' + (i+1)] = item;
});

console.log(str1); //Michael
console.log(str2); //Singh
console.log(str3); //34534DFSD3453DS

Example: http://jsfiddle/jonathon/bsnak/

No jQuery needed, just javascript:

str.split(',')

Or, to get your 3 variables:

var arr = str.split(','),
    str1 = arr[0],
    str2 = arr[1],
    str3 = arr[2];

You don't need jQuery. Javascript does that built-in via the split function.

var strarr = str.split(',');
var str1 = strarr[0];
var str2 = strarr[1];
var str3 = strarr[2];

Just use split() and store each word inside an array

var str = "Michael,Singh,34534DFSD3453DS"
var myArray = str.split(",");

// you can then manually output them using their index
alert(myarray[0]);
alert(myarray[1]);
alert(myarray[2]);

//or you can loop through them
for(var i=0; i<myArray.length; i++) {
    alert(myArray[i]);
}

It's not only that JQuery is not needed but that JQuery is not meant to do such tasks. JQuery is for HTML manipulation, animation, event handling and Ajax.

本文标签: javascriptHow to substring the string using jQueryStack Overflow