split string in two on given index and return both parts

前端 未结 8 2168
攒了一身酷
攒了一身酷 2020-12-05 12:33

I have a string that I need to split on a given index and then return both parts, seperated by a comma. For example:

string: 8211 = 8,211
        98700 = 98,         


        
8条回答
  •  孤城傲影
    2020-12-05 12:55

    If code elegance ranks higher than the performance hit of regex, then

    '1234567'.match(/^(.*)(.{3})/).slice(1).join(',')
    => "1234,567"
    

    There's a lot of room to further modify the regex to be more precise.

    If join() doesn't work then you might need to use map with a closure, at which point the other answers here may be less bytes and line noise.

提交回复
热议问题