Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combine special characters to previous index in array

Tags:

javascript

Please help javascript masters. I have an array:

["G", "A", ".", ".", ".", ".", ".", ".", "E²", "…", ".", "~", "C²", "D²", "~", "C²", "."]

and the output should be

["G", "A......", "E²….~, "C²", "D²~", "C²."]

All Dot(.), hellip(…) and tilde(~) should stick with the previous index of an array.

My current code for now is this. I don't know what to do next because I'm not familiar all the built in functions in javascript.

var newArr = ["G", "A", ".", ".", ".", ".", ".", ".", "E²", "…", ".", "~", "C²", "D²", "~", "C²", "."];

for(var i=0; i<newArr.length; i++)
  {
    if(/[\&nbsp;\&hellip;\~\.\…\*\_\/]/g.test(newArr[i]))
    {
      // delete this index and transfer current value to previous index
    }
  }
  console.log(newArr);
like image 737
enrique Avatar asked Dec 23 '22 15:12

enrique


1 Answers

This should work:

var str = ["G", "A", ".", ".", ".", ".", ".", ".", "E²", "…", ".", "~", "C²", "D²", "~", "C²", "."];

var newStr = str.join('').match(/([\w][^\w]*)/ig);
console.log(newStr);
like image 159
Mr_Green Avatar answered Feb 13 '23 22:02

Mr_Green