-3

I would like to split/extract the 8 characters which are always between the second and third comma in a string. Earlier, I split the 8 characters from 24 to 31 position in a string, but the position can vary based on the position of the commas.

Example of string:

var mystr = “1xxxxxxxx,2xxxxxxxxxxxxxx,9xxxxxxx,0xxxxxxx,XX,Rxxxxxxx,”;.

var neededcode = Code.slice(23,31);

Output should be “9xxxxxxx”.

Community
  • 1
  • 1
Sathya
  • 1
  • Okay, so what did you try? How did it fail? – David Thomas Jan 11 '19 at 07:50
  • 2
    Possible duplicate of [How do I split a string, breaking at a particular character?](https://stackoverflow.com/questions/96428/how-do-i-split-a-string-breaking-at-a-particular-character) – Jack Moody Jan 11 '19 at 07:51
  • 1
    @CertainPerformance is regex necessary here? You can just use the built-in split function to find it. – Jack Moody Jan 11 '19 at 07:57
  • 1
    @JackMoody I agree. An alternative is to also look up occurrences of commas and calculate the index range to extract. – VLAZ Jan 11 '19 at 08:00
  • 1
    @JackMoody Oh, you're right, I missed the fact that the desired match will always be between two commas. https://jsfiddle.net/o5hfy4b6/ – CertainPerformance Jan 11 '19 at 08:10

1 Answers1

2

The Javascript split() function seems to be what you are after. This function allows you to create an array. In your example, this would return ["1xxxxxxxx","2xxxxxxxxxxxxxx","9xxxxxxx","0xxxxxxx","XX","Rxxxxxxx"]. Then, to find the value after the second comma and before the third comma, you would just take the third element of the array using mystr.split(",")[2].

Code

var mystr = "1xxxxxxxx,2xxxxxxxxxxxxxx,9xxxxxxx,0xxxxxxx,XX,Rxxxxxxx,";
    
var mysplit = mystr.split(",")[2];
console.log(mysplit);

Output

9xxxxxxx

aseferov
  • 6,155
  • 3
  • 17
  • 24
Jack Moody
  • 1,590
  • 3
  • 21
  • 38