How to split and modify a string in NodeJS?

后端 未结 3 1901
北恋
北恋 2020-12-23 17:41

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:

v         


        
3条回答
  •  眼角桃花
    2020-12-23 18:10

    If you're using lodash and in the mood for a too-cute-for-its-own-good one-liner:

    _.map(_.words('123, 124, 234,252'), _.add.bind(1, 1));
    

    It's surprisingly robust thanks to lodash's powerful parsing capabilities.

    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:

    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:

    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.

提交回复
热议问题