开发者

How to substring the string using jQuery

开发者 https://www.devze.com 2023-01-30 16:38 出处:网络
I am using jQuery I have got below in my string str = \"Michael,Singh,34开发者_如何转开发534DFSD3453DS\"

I am using jQuery

I have got below in my string

str = "Michael,Singh,34开发者_如何转开发534DFSD3453DS"

Now I want my result in three variables.

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

Please suggest!

Thanks


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 recommend 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.net/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.

0

精彩评论

暂无评论...
验证码 换一张
取 消