Home > Mobile >  How to get text after the 9th occurrence of a character using javascript?
How to get text after the 9th occurrence of a character using javascript?

Time:12-21

I got the following string: NPA-Woodburn,OR,Woodburn,OR,97071,Bensenville,IL,60106,150.00,0.00,cash/certified funds,,enclosed,operable,,,,,

I need to loop through some rows and sum the 9th text after ",", but I just can't get to it. I've seen many combinations of solutions, but none gets me there.

Thank you.

CodePudding user response:

You can split the string by that character, remove all items in the array before the 9th item (with slice), then join the array back by the character.

const character = ",";

const str = "NPA-Woodburn,OR,Woodburn,OR,97071,Bensenville,IL,60106,150.00,0.00,cash/certified funds,,enclosed,operable,,,,,";

const res = str.split(character).slice(9).join(',')
console.log(res)

To isolate the 8th occurence, you can make the range in the slice call more specific:

const character = ",";

const str = "NPA-Woodburn,OR,Woodburn,OR,97071,Bensenville,IL,60106,150.00,0.00,cash/certified funds,,enclosed,operable,,,,,";

const res = str.split(character).slice(8,9)[0]
console.log(res)

  • Related