Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function splitAndMerge(string, separator) {
- //log the string and separator to see what we get:
- console.log('string: ');
- console.log(string);
- console.log('separator: ');
- console.log(separator);
- //then, split the string to words using split() function. so, a STRING: 'Hello Aviran Birnai' will turn into an ARRAY: ['Hello','Aviran','Birnai'];
- let arrayOfWords = string.split(' '); //this will split wherever there are spaces ' '
- console.log('arrayOfWords :');
- console.log(arrayOfWords);
- //empty array that the data will be saved into.
- let arrayOfWordsWithSeparator = [];
- //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).
- for (let i = 0; i < arrayOfWords.length; i++) {
- let word = arrayOfWords[i]; // i changes for each iteration (i=0, then i=1, ...)
- let arrayOfChars = word.split('') // So the String 'Aviran' will turn into ['A','v','i','r','a','n']
- 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'.
- arrayOfWordsWithSeparator.push(wordWithSeparator);// push the converted word we created to the array that exists OUTSIDE the current loop scope, so data is saved!
- }
- //now log the array we created:
- console.log('arrayOfWordsWithSeparator: ');
- console.log(arrayOfWordsWithSeparator); // ['H_e_l_l_o','A_v_i_r_a_n','B_i_r_n_a_i'];
- //combine the words of the array with space ' ' between them
- let finalString = arrayOfWordsWithSeparator.join(' ');
- console.log(finalString);
- return finalString;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement