skip to Main Content

I have a string:

this.sentence = 'I have a brother, sister, a dog, and a cat.'

I want to convert it into an array so that each word and each punctuation mark is a separate value. Using .split(" ") gives me an array of words, but does not put each comma and a dot as a separate value.

How can I do this so that I get such array

["I", "have", "a", "brother", ",", "sister", ",", "a", "dog", ",", "and", "a", "cat", "."]

I don’t really want to use .match and regex as I need to include special Polish characters in my sentences

2

Answers


  1. const string = 'I have a brother, sister, a dog, and a cat.';
    
    // Split the string into an array of words
    const result = string.split(' ');
       
    // Iterate over the array
    for (let i = 0; i < result.length; i++) {
      // Check if the word includes a comma      
      if (result[i].includes(',')) {
        // Remove the comma from the word
        result[i] = result[i].replace(',', '');
        // Insert the comma as a separate element in next position of the aray
        result.splice(i + 1, 0, ',');
        // Skip next iteration since we've added the comma and move onto next word
        i += 1;
      }
      // *Repeat same process as above but for periods
      if (result[i].includes('.')) {
        result[i] = result[i].replace('.', '');
        result.splice(i + 1, 0, '.'); 
        i += 1;
      }
    }
    console.log(result);
    Login or Signup to reply.
  2. Simple way to split them with regex

    const args = this.sentence.trim().split(/b|b(?=W)/)?.filter((e)=>e.trim() !=="");
    
    console.log(args)
    

    But, not sure if you don’t want use regex.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search