如何在NodeJS中拆分和修改字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15134199/
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
How to split and modify a string in NodeJS?
提问by Burak
I have a string :
我有一个字符串:
var str = "123, 124, 234,252";
I want to parse each item after split and increment 1. So I will have:
我想在拆分和递增 1 后解析每个项目。所以我将有:
var arr = [124, 125, 235, 253 ];
How can I do that in NodeJS?
我怎样才能在 NodeJS 中做到这一点?
回答by Micha? Miszczyszyn
Use splitand mapfunction:
用途split及map作用:
var str = "123, 124, 234,252";
var arr = str.split(",");
arr = arr.map(function (val) { return +val + 1; });
Notice +val- string is casted to a number.
注意+val- 字符串被转换为数字。
Or shorter:
或更短:
var str = "123, 124, 234,252";
var arr = str.split(",").map(function (val) { return +val + 1; });
edit 2015.07.29
编辑 2015.07.29
Today I'd advise againstusing +operator to cast variable to a number. Instead I'd go with a more explicit but also more readable Numbercall:
今天我建议不要使用+运算符将变量转换为数字。相反,我会使用更明确但也更易读的Number调用:
var str = "123, 124, 234,252";
var arr = str.split(",").map(function (val) {
return Number(val) + 1;
});
console.log(arr);
edit 2017.03.09
编辑 2017.03.09
ECMAScript 2015 introduced arrow functionso it could be used instead to make the code more concise:
ECMAScript 2015 引入了箭头函数,因此可以使用它来使代码更简洁:
var str = "123, 124, 234,252";
var arr = str.split(",").map(val => Number(val) + 1);
console.log(arr);
回答by mihaimm
var str = "123, 124, 234,252";
var arr = str.split(",");
for(var i=0;i<arr.length;i++) {
arr[i] = ++arr[i];
}
回答by Andrew Faulkner
If you're using lodash and in the mood for a too-cute-for-its-own-good one-liner:
如果你正在使用 lodash 并且想要一个过于可爱的单线:
_.map(_.words('123, 124, 234,252'), _.add.bind(1, 1));
It's surprisingly robust thanks to lodash's powerful parsing capabilities.
由于 lodash 强大的解析能力,它非常强大。
If you want one that will also clean non-digit characters out of the string (and is easier to follow...and not quite so cutesy):
如果你想要一个也可以清除字符串中的非数字字符(并且更容易理解......而且不是那么可爱):
_.chain('123, 124, 234,252, n301')
.replace(/[^\d,]/g, '')
.words()
.map(_.partial(_.add, 1))
.value();
2017 edit:
2017年编辑:
I no longer recommend my previous solution. Besides being overkill and already easy to do without a third-party library, it makes use of _.chain, which has a variety of issues. Here's the solution I would now recommend:
我不再推荐我以前的解决方案。除了矫枉过正并且在没有第三方库的情况下已经很容易做到之外,它还使用了 _.chain,它有很多问题。这是我现在推荐的解决方案:
const str = '123, 124, 234,252';
const arr = str.split(',').map(n => parseInt(n, 10) + 1);
My old answer is still correct, so I'll leave it for the record, but there's no need to use it nowadays.
我的旧答案仍然是正确的,所以我将其保留下来,但现在没有必要使用它了。

