简体   繁体   English

如何使用jQuery对字符串进行子字符串化

[英]How to substring the string using jQuery

I am using jQuery 我正在使用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: 无需jQuery,只需javascript:

str.split(',')

Or, to get your 3 variables: 或者,获取3个变量:

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

var strs = str.split(',') is your best bit. var strs = str.split(',')是您最好的选择。 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. 但是,可以通过将新项目添加到window对象中来确切地获得所需的内容。 For this I use the $.each method of jQuery. 为此,我使用jQuery的$ .each方法。 It's not necessary (you can just use a for) but I just think it's pretty :). 不必要(您可以仅使用for),但我只是认为它很漂亮:)。 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/ 示例: http//jsfiddle.net/jonathon/bsnak/

You don't need jQuery. 您不需要jQuery。 Javascript does that built-in via the split function . Javascript通过split函数内置了该功能

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 只需使用split()并将每个单词存储在数组中

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,而且JQuery并非要执行此类任务。 JQuery is for HTML manipulation, animation, event handling and Ajax. JQuery用于HTML操作,动画,事件处理和Ajax。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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