如何使用 JavaScript 拆分逗号分隔的字符串并循环处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3245088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:50:37  来源:igfitidea点击:

How to split a comma separated string and process in a loop using JavaScript

javascript

提问by DEVOPS

How to split a comma separated string and process in a loop using JavaScript?

如何使用 JavaScript 拆分逗号分隔的字符串并循环处理?

回答by kzh

My two cents, adding trim to remove the initial whitespaces left in sAc's answer.

我的两分钱,添加修剪以删除 sAc 答案中留下的初始空格。

var str = 'Hello, World, etc';
var str_array = str.split(',');

for(var i = 0; i < str_array.length; i++) {
   // Trim the excess whitespace.
   str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
   // Add additional code here, such as:
   alert(str_array[i]);
}

Edit:

编辑:

After getting several upvotes on this answer, I wanted to revisit this. If you want to split on comma, and perform a trim operation, you can do it in one method call without any explicit loops due to the fact that splitwill also take a regular expression as an argument:

在对这个答案获得数次赞成后,我想重新审视这个问题。如果您想在逗号上拆分并执行修剪操作,您可以在一个方法调用中完成,而无需任何显式循环,因为它split也将使用正则表达式作为参数:

'Hello, cruel , world!'.split(/\s*,\s*/);
//-> ["Hello", "cruel", "world!"]

This solution, however, will not trim the beginning of the first item and the end of the last item which is typically not an issue.

但是,此解决方案不会修剪第一个项目的开头和最后一个项目的结尾,这通常不是问题。

And so to answer the question in regards to process in a loop, if your target browsers support ES5 array extras such as the mapor forEachmethods, then you could just simply do the following:

因此,要回答有关循环处理的问题,如果您的目标浏览器支持 ES5 数组附加项,例如maporforEach方法,那么您只需执行以下操作:

myStringWithCommas.split(/\s*,\s*/).forEach(function(myString) {
    console.log(myString);
});

回答by Sarfraz

Like this:

像这样:

var str = 'Hello, World, etc';
var myarray = str.split(',');

for(var i = 0; i < myarray.length; i++)
{
   console.log(myarray[i]);
}

回答by Anax

Try the following snippet:

尝试以下代码段:

var mystring = 'this,is,an,example';
var splits = mystring.split(",");
alert(splits[0]); // output: this

回答by Renish Gotecha

Please run below code may it helps you :)

请运行下面的代码可能对你有帮助:)

var str = "this,is,an,example";
var strArr = str.split(',');
var data = "";
for(var i=0; i<strArr.length; i++){
  data += "Index : "+i+" value : "+strArr[i]+"<br/>";
}
document.getElementById('print').innerHTML = data;
<div id="print">
</div>

回答by Aakash Sajjad

you can Try the following snippet:

您可以尝试以下代码段:

var str = "How are you doing today?";
var res = str.split("o");
console.log("My Result:",res)

and your output like that

和你的输出

My Result: H,w are y,u d,ing t,day?