1

I am trying to join the 2nd and 3rd elements into one on the array i.e: [567, "O/S", '1,111']

Possible strings: 567/O/S/1,111 / 5/O/S/1,111 (The first element in the array could be up to 4 digits long)

I've got this working below but its not a very eloquent solution, is there a better way to do this? Possibly an es6 array function?

var array = '567/O/S/1,111'.split('/') if(array.length > 3) { var text1 = array[1]; var text2 = array[2]; var joinedText = `${text1}/${text2}`; array.splice(1,2); array.splice(1, 0, joinedText); } console.log(array) //[567, "O/S", '1,111'] 

1 Answer 1

3

You could use a regular expression to either match a letter, followed by a slash and another letter, or anything but a slash:

console.log( '567/O/S/1,111'.match(/[a-z]\/[a-z]|[^/]+/gi), ); console.log( '5/O/S/1,111'.match(/[a-z]\/[a-z]|[^/]+/gi), );

  • [a-z]\/[a-z] - a letter, followed by a slash, followed by another letter
  • [^/]+ - one or more non-slash characters
Sign up to request clarification or add additional context in comments.

3 Comments

This don't work in case there would be 3 chunks after split. 567/O/1,111. OP has if(array.length > 3) in his code
This is really good thankyou! I should have mentioned the first element in the array could be between 1-4 digits long which the regex expression above fails on it produces ["5/O", "S/1", ",111" ]
@NoDachi See edit, I guess you need [a-z] instead of \w

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.