简体   繁体   中英

How to substring the string using jQuery

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

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

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/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM