Advertisement
ncamaa1

Untitled

Dec 2nd, 2021
1,406
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function splitAndMerge(string, separator) {
  2.   //log the string and separator to see what we get:
  3.   console.log('string: ');
  4.   console.log(string);
  5.   console.log('separator: ');
  6.   console.log(separator);
  7.  
  8.   //then, split the string to words using split() function. so, a STRING: 'Hello Aviran Birnai' will turn into an ARRAY: ['Hello','Aviran','Birnai'];
  9.   let arrayOfWords = string.split(' '); //this will split wherever there are spaces ' '
  10.   console.log('arrayOfWords :');
  11.   console.log(arrayOfWords);
  12.  
  13.   //empty array that the data will be saved into.
  14.   let arrayOfWordsWithSeparator = [];
  15.  
  16.   //iterate over each word, split it into characters, then join with the separator. So, for example, 'Hello' will turn into 'H-e-l-l-o'/ . A reminder, what ever inside the scope of the function {...} will run X times (X is the length of the Array).
  17.   for (let i = 0; i < arrayOfWords.length; i++) {
  18.     let word = arrayOfWords[i]; // i changes for each iteration (i=0, then i=1, ...)
  19.     let arrayOfChars = word.split('') // So the String 'Aviran' will turn into ['A','v','i','r','a','n']
  20.     let wordWithSeparator = word.join(separator) // depends on the variable separator - this will join the former array to a single String. So, if the separator='_' ['A','v','i','r','a','n'] will turn into 'A_v_i_r_a_n'.
  21.     arrayOfWordsWithSeparator.push(wordWithSeparator);// push the converted word we created to the array that exists OUTSIDE the current loop scope, so data is saved!
  22.   }
  23.  
  24.   //now log the array we created:
  25.   console.log('arrayOfWordsWithSeparator: ');
  26.   console.log(arrayOfWordsWithSeparator); // ['H_e_l_l_o','A_v_i_r_a_n','B_i_r_n_a_i'];
  27.  
  28.   //combine the words of the array with space ' ' between them
  29.   let finalString = arrayOfWordsWithSeparator.join(' ');
  30.   console.log(finalString);
  31.  
  32.   return finalString;
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement