如何使用JavaScript在循环中拆分逗号分隔的字符串和进程 [英] How to split a comma separated string and process in a loop using JavaScript
问题描述
如何使用JavaScript在循环中拆分逗号分隔的字符串和进程?
How to split a comma separated string and process in a loop using JavaScript?
推荐答案
我的两分钱,添加修剪到删除sAc答案中留下的初始空格。
My two cents, adding trim to remove the initial whitespaces left in sAc's answer.
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]);
}
编辑:
在得到这个答案的几个赞成之后,我想重新审视这个问题。如果你想在逗号上拆分,并执行修剪操作,你可以在一个方法调用中完成它而不需要任何显式循环,因为 split
也会定期表达式作为参数:
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 split
will also take a regular expression as an argument:
'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.
所以回答有关循环过程的问题,如果您的目标浏览器支持ES5数组附加功能,例如 map
或 forEach
方法,那么您只需执行以下操作即可:
And so to answer the question in regards to process in a loop, if your target browsers support ES5 array extras such as the map
or forEach
methods, then you could just simply do the following:
myStringWithCommas.split(/\s*,\s*/).forEach(function(myString) {
console.log(myString);
});
这篇关于如何使用JavaScript在循环中拆分逗号分隔的字符串和进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!