4

Relative newcomer to Javascript and a bit stuck with the following so would greatly appreciate some help...

I have a string made up of a list of categories and keywords which might appear like:

Category A:Keyword A, Category B:, Category C: Keyword B

The problem is displaying a category when there is no keyword - how can I do a Find and Replace to swap instances of :, with just ,?

I already use the following to insert a space after the comma:

cats = cats.replace(/,/g,", ");

but copying and modifying with the extra colon seems to break it...

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
neil
  • 1,246
  • 1
  • 12
  • 20

2 Answers2

6

Use:

cats = cats.replace(/:\s*,/g,", ");
xdazz
  • 158,678
  • 38
  • 247
  • 274
1

I think you should use arrays:

var arr="Category A:Keyword A, Category B:, Category C:Keyword B".split(', ');
for(var i=0;i<arr.length;i++){
   arr[i]=arr[i].split(':');
}

Then, arr becomes [["Category A", "Keyword A"], ["Category B", ""], ["Category C", "Keyword B"]]