user12351507
user12351507

Reputation:

How to split and insert numbers in each splitted string (javascript)?

I want to split both the following string and put the index number in each with the . (dot) at the end.

let str1 = "1. sun ; moon ; star ; god ; goddess";

// will work with both the string

let str2 = "sun; moon; star; god; goddess;";

Result should be like this

let result = "1. sun\n2. moon\n3. star\n4. god\n5. goddess.";

Or as below if executed

1. sun.
2. moon.
3. star.
4. god.
5. goddess.

Update: I splitted it but failed to put the index number in each word. Since the words are random e.g. one can have 3 words and other can have the 5 words and so on...

Upvotes: 1

Views: 120

Answers (2)

ggorlen
ggorlen

Reputation: 56895

We can split on the regex /\s*;\s*/g, then handle the possibility that the number may already exist on the list item in the map function, as is the case in the first example.

let str1 = "1. sun ; a moon ; star ; god ; goddess ; ";

const result = str1.split(/\s*;\s*/g)
  .filter(Boolean)
  .map((e, i) => `${/^\d+\./.test(e) ? "" : i + 1 + ". "}${e}.`)
  .join("\n");

console.log(result);

Upvotes: 0

giuseppedeponte
giuseppedeponte

Reputation: 2391

You can achieve that by removing the list numbers from the string before adding them back. Here is an example :

const formatList = list => {
  list = list
    // split the string
    .split(';')
    // filter out empty list items
    .filter(Boolean)
    // Iterate over the list items to format them
    .map((item, index) => {
      // Start with the index (+1 one to start from 1)
      return (index + 1)
        // Add the dot and the space
        +
        '. '
        // Add the list item without any number+dot substring and any extra space
        +
        item.replace(/\d+\./g, '').trim()
        // Add a final dot (even if list should not usually have ending dots)
        +
        '.'
    })
    // Join back the list items with a newline between each
    .join('\n');

  return list;
};

let str1 = "1. sun ; moon ; star ; god ; goddess";

let str2 = "sun; moon; star; god; goddess;";

let result = "1. sun.\n2. moon.\n3. star.\n4. god.\n5. goddess.";

console.log(formatList(str1), formatList(str1) === result);
console.log(formatList(str2), formatList(str2) === result);

Upvotes: 1

Related Questions