-1

I am doing some homework problems using JavaScript. I need to do some string and array manipulation. I've solved similar problems in PHP using the explode and implode functions. Is there something similar that I can use in JavaScript?

Here is a sample of my code (simplified for this question). I'll use explode and implode even though they are not available in JS:

function getHashtags(str) {
  let words = explode(' ', str);
  let hashtags = [];
  words.forEach((word) => {
    if (word[0] === '#') {
      hashtags.push(word);
    }
  });
}

function generateSentence() {
  let subjects = ['He', 'She', 'John', 'Jane', 'The girl', 'The boy', 'The dog'];
  let verbs = ['ran', 'jumped', 'ate', 'danced', 'played', 'laughed'];
  let adverbs = ['quickly', 'happily', 'merrily', 'slowly'];

  const random = (length) => Math.floor(Math.random()*length);
  let result = [];
  result.push(subjects[random(subjects.length)]);
  result.push(verbs[random(verbs.length)]);
  result.push(adverbs[random(adverbs.length)]);

  return implode(' ', result) + '.';
}

1 Answers1

1

JavaScript has the String.split and Array.join functions.

String.split is a lot like php's explode. It takes a single parameter: a string delimiter to split on. In your case you could swap out explode for split:

function getHashtags(str) {
  let words = str.split(' ');
  let hashtags = [];
  words.forEach((word) => {
    if (word[0] === '#') {
      hashtags.push(word);
    }
  });
}

For implode, Array.join is very similar. This function also takes a single (optional) parameter: a string to place between each element of the array when they are joined together. If this parameter is omitted, the elements of the array are joined together without anything in between. You could swap out your call to implode for join.

However, I should point out that you do not need to use an array for this. Since the desired result is a string, why not just use string concatenation to solve this, without using an array first? Something like this:

function generateSentence() {
  let subjects = ['He', 'She', 'John', 'Jane', 'The girl', 'The boy', 'The dog'];
  let verbs = ['ran', 'jumped', 'ate', 'danced', 'played', 'laughed'];
  let adverbs = ['quickly', 'happily', 'merrily', 'slowly'];

  const random = (length) => Math.floor(Math.random()*length);
  let result = "";
  result += subjects[random(subjects.length)] + " ";
  result += verbs[random(verbs.length)] + " ";
  result += adverbs[random(adverbs.length)] ".";

  return result;
}
Vince
  • 3,207
  • 1
  • 17
  • 28